import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.vdn import VDNMixer
from modules.mixers.qmix import QMixer
import torch
from torch.optim import RMSprop
import torch.nn.functional as F
#from modules.critics.feudal_critic import FeudalCritic

import numpy as np

class FeudalLearner:
    def __init__(self, mac, scheme, logger, args):
        self.args = args
        self.mac = mac
        self.logger = logger

        self.manager_params = list(mac.manager_parameters())
        self.worker_params = list(mac.worker_parameters())


        self.last_target_update_episode = 0

        self.mixer = None
        if args.mixer is not None:
            if args.mixer == "vdn":
                self.mixer = VDNMixer()
            elif args.mixer == "qmix":
                self.mixer = QMixer(args)
            else:
                raise ValueError("Mixer {} not recognised.".format(args.mixer))
            self.worker_params += list(self.mixer.parameters())
            self.target_mixer = copy.deepcopy(self.mixer)

                # Optimise manager's parameters
        self.manager_optimiser = RMSprop(params=self.manager_params, lr=self.args.lr, alpha=self.args.optim_alpha, eps=self.args.optim_eps)
        self.worker_optimiser = RMSprop(params=self.worker_params, lr=self.args.lr, alpha=self.args.optim_alpha, eps=self.args.optim_eps)

        # a little wasteful to deepcopy (e.g. duplicates action selector), but should work for any MAC
        self.target_mac = copy.deepcopy(mac)

        self.enable_parallel_computing = (not self.args.use_cuda) and getattr(self.args, 'enable_parallel_computing',
                                                                              False)
        # self.enable_parallel_computing = False
        if self.enable_parallel_computing:
            from multiprocessing import Pool
            # Multiprocessing pool for parallel computing.
            self.pool = Pool(1)
        
        self.log_stats_t = -self.args.learner_log_interval - 1

    def train(self, batch: EpisodeBatch, t_env: int, episode_num: int, show_demo=False, save_data=None):
        if self.args.use_cuda and str(self.mac.get_device()) == "cpu":
            self.mac.cuda()

        # Get the relevant quantities
        rewards = batch["reward"][:, :-1]
        actions = batch["actions"][:, :-1]
        terminated = batch["terminated"][:, :-1].float()
        mask = batch["filled"][:, :-1].float()
        mask[:, 1:] = mask[:, 1:] * (1 - terminated[:, :-1])
        avail_actions = batch["avail_actions"]

        states = batch["obs"][:, :-1]  # 倒數第二個時間步
        next_states = batch["obs"][:, 1:]  # 最後一個時間步

        # Calculate estimated Q-Values
        mac_out, goals_out, values_out = [], [], []
        self.mac.init_hidden(batch.batch_size)
        for t in range(batch.max_seq_length):
            agent_outs, goals, values = self.mac.forward(batch, t=t)
            mac_out.append(agent_outs)
            goals_out.append(goals)
            values_out.append(values)
        mac_out = torch.stack(mac_out, dim=1)  # Concat over time
        goals_out = torch.stack(goals_out, dim=1)  # Concat over time
        values_out = torch.stack(values_out, dim=1)  # Concat over time


        # Use goal_out to influence action selection or target calculation
        # Example: Modify chosen_action_qvals calculation using goal_out
        chosen_action_qvals = torch.gather(mac_out[:, :-1], dim=3, index=actions).squeeze(3)  # Remove the last dim
        # Modify chosen_action_qvals with goal_out if necessary
        # chosen_action_qvals = some_function(chosen_action_qvals, goal_out)

        x_mac_out = mac_out.clone().detach()
        x_mac_out[avail_actions == 0] = -9999999
        max_action_qvals, max_action_index = x_mac_out[:, :-1].max(dim=3)

        max_action_index = max_action_index.detach().unsqueeze(3)
        is_max_action = (max_action_index == actions).int().float()

        if show_demo:
            q_i_data = chosen_action_qvals.detach().cpu().numpy()
            q_data = (max_action_qvals - chosen_action_qvals).detach().cpu().numpy()

        # Calculate the Q-Values necessary for the target
        target_mac_out = []
        self.target_mac.init_hidden(batch.batch_size)
        for t in range(batch.max_seq_length):
            target_agent_outs, _, _ = self.target_mac.forward(batch, t=t)
            target_mac_out.append(target_agent_outs)

        # We don't need the first timesteps Q-Value estimate for calculating targets
        target_mac_out = torch.stack(target_mac_out[1:], dim=1)  # Concat across time

        # Max over target Q-Values
        if self.args.double_q:
            # Get actions that maximise live Q (for double q-learning)
            mac_out_detach = mac_out.clone().detach()
            mac_out_detach[avail_actions == 0] = -9999999
            cur_max_actions = mac_out_detach[:, 1:].max(dim=3, keepdim=True)[1]
            target_max_qvals = torch.gather(target_mac_out, 3, cur_max_actions).squeeze(3)
        else:
            target_max_qvals = target_mac_out.max(dim=3)[0]

        # Mix
        if self.mixer is not None:
            chosen_action_qvals = self.mixer(chosen_action_qvals, batch["state"][:, :-1])
            target_max_qvals = self.target_mixer(target_max_qvals, batch["state"][:, 1:])

        if show_demo:
            tot_q_data = chosen_action_qvals.detach().cpu().numpy()
            tot_target = targets.detach().cpu().numpy()
            if self.mixer == None:
                tot_q_data = np.mean(tot_q_data, axis=2)
                tot_target = np.mean(tot_target, axis=2)

            print('action_pair_%d_%d' % (save_data[0], save_data[1]), np.squeeze(q_data[:, 0]),
                  np.squeeze(q_i_data[:, 0]), np.squeeze(tot_q_data[:, 0]), np.squeeze(tot_target[:, 0]))
            self.logger.log_stat('action_pair_%d_%d' % (save_data[0], save_data[1]),
                                 np.squeeze(tot_q_data[:, 0]), t_env)
            return

        #----------------------------- Calculate worker loss -----------------------------------
        # 1. 計算內部獎勵
        c = self.args.c  # c 步數
        states = batch["obs"][:, :-c]  # s_t
        future_states = batch["obs"][:, c:]  # s_{t+c}
        state_diff = future_states - states  # 計算狀態差異
        goals = goals_out[:, :-c]  # 對應時間步的目標
        # print("state_diff.shape: ", state_diff.shape)
        # print("goals.shape: ", goals.shape)

        # 計算內部獎勵 (使用餘弦相似度)
        temp_state_diff = state_diff.reshape(-1, self.args.state_dim)
        temp_goals = goals.reshape(-1, self.args.state_dim)
        cos_sim = F.cosine_similarity(temp_state_diff, temp_goals, dim=-1)
        cos_sim = cos_sim.view(state_diff.shape[0], state_diff.shape[1], -1)
        intrinsic_rewards = (cos_sim / c).mean(dim=2, keepdim=True)

        # 2. 組合內部和外部獎勵
        combined_rewards = (1 - self.args.intrinsic_rewards_alpha) * rewards + \
                          self.args.intrinsic_rewards_alpha * intrinsic_rewards

        # 3. 使用組合獎勵計算 TD 誤差
        targets = combined_rewards + self.args.gamma * (1 - terminated) * target_max_qvals
        td_error = (chosen_action_qvals - targets.detach())
        mask = mask.expand_as(td_error)
        # 0-out the targets that came from padded data
        masked_td_error = td_error * mask
        worker_loss = (masked_td_error ** 2).sum()

        # 4. 優化 Worker
        self.worker_optimiser.zero_grad()
        worker_loss.backward(retain_graph=True)
        grad_norm_worker = torch.nn.utils.clip_grad_norm_(self.worker_params, self.args.grad_norm_clip)
        self.worker_optimiser.step()
        

        masked_hit_prob = torch.mean(is_max_action, dim=2) * mask
        hit_prob = masked_hit_prob.sum() / mask.sum()

        #----------------------------- Calculate manager loss -----------------------------------
        # 1. 計算狀態差異和目標
        states = batch["obs"][:, :-c]  # s_t
        future_states = batch["obs"][:, c:]  # s_{t+c}
        state_diff = future_states - states
        goals = goals_out[:, :-c]
        values = values_out[:, :-c]  # 使用 manager 輸出的 values

        # 2. 計算優勢函數 - 為每個agent分別計算
        rewards_expanded = rewards.unsqueeze(2).expand(-1, -1, self.args.n_agents, -1).squeeze(-1)  # [batch_size, seq_len-1, n_agents]

        # values_out: [batch_size, seq_len-1, n_agents]
        next_values = values_out[:, c:].squeeze(-1)           # [batch_size, seq_len-c, n_agents]
        current_values = values.squeeze(-1)                    # [batch_size, seq_len-c, n_agents]

        # 3. 為每個agent計算目標值和優勢
        target_values = rewards_expanded + (self.args.gamma ** c) * next_values  # [batch_size, seq_len-c, n_agents]
        advantages = rewards_expanded - current_values  # [batch_size, seq_len-c, n_agents]

        # 4. 計算策略梯度
        temp_state_diff = state_diff.reshape(-1, self.args.state_dim)
        temp_goals = goals.reshape(-1, self.args.state_dim)
        cos_sim = F.cosine_similarity(temp_state_diff, temp_goals, dim=-1)
        cos_sim = cos_sim.view(state_diff.shape[0], state_diff.shape[1], -1)  # [batch_size, seq_len-c, n_agents]

        # 5. Manager 的損失
        value_loss = F.mse_loss(current_values, target_values.detach())
        manager_loss = -(advantages.detach() * cos_sim).sum()
        total_manager_loss = manager_loss + self.args.vf_coef * value_loss

        # 6. 優化 Manager
        self.manager_optimiser.zero_grad()
        total_manager_loss.backward()
        grad_norm_manager = torch.nn.utils.clip_grad_norm_(self.manager_params, self.args.grad_norm_clip)
        self.manager_optimiser.step()


        if (episode_num - self.last_target_update_episode) / self.args.target_update_interval >= 1.0:
            self._update_targets()
            self.last_target_update_episode = episode_num

        if t_env - self.log_stats_t >= self.args.learner_log_interval:
            self.logger.log_stat("worker_loss", worker_loss.item(), t_env)
            self.logger.log_stat("manager_loss", total_manager_loss.item(), t_env)
            self.logger.log_stat("manager_cos_sim", cos_sim.mean().item(), t_env)
            self.logger.log_stat("manager_advantage", advantages.mean().item(), t_env)
            self.logger.log_stat("hit_prob", hit_prob.item(), t_env)
            self.logger.log_stat("grad_norm_manager", grad_norm_manager, t_env)
            self.logger.log_stat("grad_norm_worker", grad_norm_worker, t_env)
            mask_elems = mask.sum().item()
            self.logger.log_stat("td_error_abs", (masked_td_error.abs().sum().item()/mask_elems), t_env)
            self.logger.log_stat("q_taken_mean", (chosen_action_qvals * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)
            self.logger.log_stat("target_mean", (targets * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)
            self.log_stats_t = t_env


    def _update_targets(self):
        self.target_mac.load_state(self.mac)
        if self.mixer is not None:
            self.target_mixer.load_state_dict(self.mixer.state_dict())
        self.logger.console_logger.info("Updated target network")

    def cuda(self):
        self.mac.cuda()
        self.target_mac.cuda()
        if self.mixer is not None:
            self.mixer.cuda()
            self.target_mixer.cuda()

    def save_models(self, path):
        self.mac.save_models(path)
        if self.mixer is not None:
            torch.save(self.mixer.state_dict(), "{}/mixer.torch".format(path))
        torch.save(self.worker_optimiser.state_dict(), "{}/worker_opt.torch".format(path))
        torch.save(self.manager_optimiser.state_dict(), "{}/manager_opt.torch".format(path))

    def load_models(self, path):
        self.mac.load_models(path)
        # Not quite right but I don't want to save target networks
        self.target_mac.load_models(path)
        if self.mixer is not None:
            self.mixer.load_state_dict(torch.load("{}/mixer.torch".format(path), map_location=lambda storage, loc: storage))
        self.worker_optimiser.load_state_dict(torch.load("{}/worker_opt.torch".format(path), map_location=lambda storage, loc: storage))
        self.manager_optimiser.load_state_dict(torch.load("{}/manager_opt.torch".format(path), map_location=lambda storage, loc: storage))
