import copy
from components.episode_buffer import EpisodeBatch
from modules.mixers.vdn import VDNMixer
from modules.mixers.qmix import QMixer

import torch as th
import torch.nn.functional as F
from torch.optim import RMSprop, Adam
from utils.rl_utils import build_td_lambda_targets, build_td_lambda_targets_with_weights
import numpy as np
import pdb
from collections import deque


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

        self.params = list(mac.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.params += list(self.mixer.parameters())
            self.target_mixer = copy.deepcopy(self.mixer)
        if self.args.optim == 'RMSProp':
            self.optimiser = RMSprop(params=self.params, lr=args.lr, alpha=args.optim_alpha, eps=args.optim_eps)
        elif self.args.optim == 'Adam':
            self.optimiser = Adam(params=self.params, lr=args.lr)
        # a little wasteful to deepcopy (e.g. duplicates action selector), but should work for any MAC
        self.target_mac = copy.deepcopy(mac)

        self.log_stats_t = -self.args.learner_log_interval - 1

        # LFIW parameters
        self.lfiw_optimiser = Adam(params=mac.lfiw_parameters(), lr=args.lfiw_lr)
        self.prob_temperature = self.args.prob_temperature
        # lambda parameters
        self.buffer = buffer
        self.max_discounted_return = 0

    def train(self, batch: EpisodeBatch, fast_batch: EpisodeBatch, t_env: int, episode_num: int, ids: list):
        # 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"]
        weights = batch["td_lambda"]

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

        # Pick the Q-Values for the actions taken by each agent
        chosen_action_qvals = th.gather(mac_out[:, :-1], dim=3, index=actions).squeeze(3)  # Remove the last dim

        # Calculate the Q-Values necessary for the target
        target_mac_out = []
        target_policies = []
        self.target_mac.init_hidden(batch.batch_size)
        for t in range(batch.max_seq_length):
            target_agent_outs, target_policy = self.target_mac.forward(batch, t=t)
            target_mac_out.append(target_agent_outs)
            target_policies.append(target_policy)
        # We don't need the first timesteps Q-Value estimate for calculating targets
        target_mac_out = th.stack(target_mac_out, dim=1)  # Concat across time
        target_policies = th.stack(target_policies, dim=1)
        
        # Mask out unavailable actions
        target_mac_out[avail_actions == 0] = -9999999
        # 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.max(dim=3, keepdim=True)[1]
            target_max_qvals = th.gather(target_mac_out, 3, cur_max_actions).squeeze(3)
            target_policies = th.gather(target_policies, 3, cur_max_actions).squeeze(3)
        else:
            target_max_qvals = target_mac_out.max(dim=3)[0]
            target_policies = target_policies.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"])
        

        if self.args.dyn_td_lambda:

            targets = rewards + self.args.gamma * (1 - terminated) * target_max_qvals[:, 1:].detach()
            delta_td = (chosen_action_qvals - targets).detach()
            
            delta = 1 - th.exp(-th.abs(delta_td))

            delta_expand = th.zeros_like(target_max_qvals)
            delta_expand[:, :delta.size(1),] = delta

            delta_expand = delta_expand / th.mean(delta_expand)
            '''
            delta = self.cal_delta(batch, target_max_qvals)
            delta_expand = delta.T.expand(target_max_qvals.size(1), target_max_qvals.size(0)).T
            '''


            #new_weights = self.update_lfiw(fast_batch, batch) * delta.unsqueeze(dim=-1).detach() * policy_weights.unsqueeze(dim=-1).detach()
            lambda_weights, MSE_weights = self.update_lfiw(fast_batch, batch)

            new_weights = th.clamp(lambda_weights * delta_expand.detach(), min=0.0, max=1.0)
            #new_weights = lambda_weights * delta.unsqueeze(dim=-1).detach()
            


            td_lambda = th.where(weights==0, new_weights, weights)
            

            for t in range(weights.size(1)):
                self.buffer.update({"td_lambda": td_lambda[:, t]}, bs=ids, ts=t, mark_filled=False)

                
            #targets = build_td_lambda_targets(rewards, terminated, mask, target_max_qvals, self.args.n_agents, self.args.gamma, self.td_lambda)
            targets = build_td_lambda_targets_with_weights(rewards, terminated, mask, target_max_qvals, self.args.n_agents, self.args.gamma, td_lambda)
        else:
            # Calculate 1-step Q-Learning targets
            zeros_lambda = th.zeros_like(weights) + self.args.td_lambda
            targets = build_td_lambda_targets_with_weights(rewards, terminated, mask, target_max_qvals, self.args.n_agents, self.args.gamma, zeros_lambda)

            # Td-error

    
        td_error = (chosen_action_qvals - targets[:,:-1])

        mask = mask.expand_as(td_error)

        # 0-out the targets that came from padded data
        masked_td_error = td_error * mask

        # Normal L2 loss, take mean over actual data
        if self.args.dyn_td_lambda and self.args.use_weight:
            loss = (MSE_weights[:, :-1] * (masked_td_error ** 2)).sum() / mask.sum()
        else:
            loss = (masked_td_error ** 2).sum() / mask.sum()

        # Optimise
        self.optimiser.zero_grad()
        loss.backward()
        grad_norm = th.nn.utils.clip_grad_norm_(self.params, self.args.grad_norm_clip)
        self.optimiser.step()

        if (episode_num - self.last_target_update_episode) / self.args.target_update_interval >= 1.0:
            self.buffer.clear_lambda()
            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("loss", loss.item(), t_env)
            # self.logger.log_stat("grad_norm", grad_norm, 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[:, :-1] * mask).sum().item()/(mask_elems * self.args.n_agents), t_env)
            self.log_stats_t = t_env

    def update_lfiw(self, fast_batch, slow_batch):
        slow_outs = []
        fast_outs = []
        self.mac.LFIW_init_hidden(slow_batch.batch_size)
        for t in range(fast_batch.max_seq_length):
            slow_out = self.mac.LFIW_forward(slow_batch, t).reshape(-1, 1)       # [bs * T, 1]

            slow_outs.append(slow_out)
        
        slow_outs = th.stack(slow_outs, dim=1)


        self.mac.LFIW_init_hidden(fast_batch.batch_size)
        for t in range(fast_batch.max_seq_length):
            fast_out = self.mac.LFIW_forward(fast_batch, t).reshape(-1, 1)

            fast_outs.append(fast_out)

        fast_outs = th.stack(fast_outs, dim=1)

        zeros = th.zeros_like(slow_outs).to(self.args.device)
        ones = th.ones_like(fast_outs).to(self.args.device)

        loss = F.binary_cross_entropy(F.sigmoid(slow_outs), zeros) + F.binary_cross_entropy(F.sigmoid(fast_outs), ones)
        

        self.lfiw_optimiser.zero_grad()
        loss.backward(retain_graph=False)
        self.lfiw_optimiser.step()

        self.mac.LFIW_init_hidden(slow_batch.batch_size)
        slow_preds = []
        for t in range(slow_batch.max_seq_length):
            slow_pred = self.mac.LFIW_forward(slow_batch, t).reshape(-1, 1)
            slow_preds.append(slow_pred)
        slow_preds = th.stack(slow_preds, dim=1)

        importance_weights = F.sigmoid(slow_preds/self.prob_temperature).detach()
        lambda_weights = importance_weights.clone()

        #lambda_weights = (lambda_weights - self.min_weight) / (self.max_weight - self.min_weight)
        #lambda_weights = th.minimum(th.maximum((lambda_weights / th.mean(lambda_weights) - 1), th.zeros_like(lambda_weights)), th.ones_like(lambda_weights))
        #lambda_weights = th.nn.functional.softmax(lambda_weights / th.mean(lambda_weights) - 1, dim=1)

        #print(th.max(lambda_weights), th.min(lambda_weights), th.median(lambda_weights))
         
        MSE_weights = F.sigmoid(slow_preds/5.0).detach()
        MSE_weights = MSE_weights / th.mean(MSE_weights)
        #print(lambda_weights)
        return lambda_weights, MSE_weights
    

    def cal_delta(self, batch, target_agent_qval):
        
        rewards = batch['reward']
        terminated = batch['terminated']
        discounted_returns = target_agent_qval.new_zeros(*target_agent_qval.shape)
        discounted_returns[:, -1] = target_agent_qval[:, -1] * (1 - th.sum(terminated, dim=1))
        
        for i in range(rewards.size(1) - 2, -1, -1):
            discounted_returns[:, i] = rewards[:, i] + self.args.gamma * discounted_returns[:, i+1]

        self.max_discounted_return = max(self.max_discounted_return, th.max(discounted_returns[:, 0]).item())
        
        delta = th.exp(-th.abs(discounted_returns[:, 0] - self.max_discounted_return))

        delta = delta / th.mean(delta)

        return delta
    
    
    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:
            th.save(self.mixer.state_dict(), "{}/mixer.th".format(path))
        th.save(self.optimiser.state_dict(), "{}/opt.th".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(th.load("{}/mixer.th".format(path), map_location=lambda storage, loc: storage))
        self.optimiser.load_state_dict(th.load("{}/opt.th".format(path), map_location=lambda storage, loc: storage))
