import numpy as np
import torch
import torch.nn.functional as F

import sys, os
python_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'torch-irl/')
sys.path.append(python_path)
 
from torch_irl.algos.base import BaseAlgo
 
def kl_divergence(mu, logvar):
    kl_div = 0.5 * torch.sum(mu.pow(2) + logvar.exp() - logvar - 1, dim=1)
    return kl_div

class VAILAlgo(BaseAlgo):
    """The Proximal Policy Optimization algorithm
    ([Schulman et al., 2015](https://arxiv.org/abs/1707.06347))."""

    def __init__(self, envs, acmodel, discmodel, device=None, num_frames_per_proc=None, discount=0.99, lr=0.001, gae_lambda=0.95,
                 i_c = 0.5, alpha_beta = 1e-4,
                 entropy_coef=0.01, value_loss_coef=0.5, max_grad_norm=0.5, ac_recurrence=4, disc_recurrence = 4,
                 adam_eps=1e-8, clip_eps=0.2, epochs=4, batch_size=256, preprocess_obss=None,
                 reshape_reward=None, entropy_reward = False):
        num_frames_per_proc = num_frames_per_proc or 128
        
        super().__init__(envs, acmodel, discmodel, device, num_frames_per_proc, discount, lr, gae_lambda, entropy_coef,
                         value_loss_coef, max_grad_norm, ac_recurrence, disc_recurrence, preprocess_obss, reshape_reward, entropy_reward)
        self.i_c = i_c
        self.alpha_beta = alpha_beta
        self.beta = 0
        self.clip_eps = clip_eps
        self.epochs = epochs
        self.batch_size = batch_size
 
        assert self.batch_size % self.ac_recurrence == 0 and self.batch_size % self.disc_recurrence == 0
        
        self.ac_optimizer = torch.optim.Adam(self.acmodel.parameters(), lr, eps=adam_eps)
        self.disc_optimizer = torch.optim.Adam(self.discmodel.parameters(), lr, eps=adam_eps)
        self.batch_num = 0
 

    def update_ac_parameters(self, exps):
        # Collect experiences

        for _ in range(self.epochs):
            # Initialize log values

            log_entropies = []
            log_values = []
            log_policy_losses = []
            log_value_losses = []
            log_grad_norms = []

            for inds in self._get_batches_starting_indexes(self.ac_recurrence):
                # Initialize batch values

                batch_entropy = 0
                batch_value = 0
                batch_policy_loss = 0
                batch_value_loss = 0
                batch_loss = 0

                # Initialize memory

                if self.acmodel.recurrent:
                    memory = exps.ac_memory[inds]

                for i in range(self.ac_recurrence):
                    # Create a sub-batch of experience

                    sb = exps[inds + i]

                    # Compute loss

                    if self.acmodel.recurrent:
                        dist, value, memory = self.acmodel(sb.obs, memory * sb.mask)
                    else:
                        dist, value = self.acmodel(sb.obs)

                    entropy = dist.entropy().mean()

                    ratio = torch.exp(dist.log_prob(sb.action) - sb.log_prob)
                    surr1 = ratio * sb.advantage
                    surr2 = torch.clamp(ratio, 1.0 - self.clip_eps, 1.0 + self.clip_eps) * sb.advantage
                    policy_loss = -torch.min(surr1, surr2).mean()

                    value_clipped = sb.value + torch.clamp(value - sb.value, -self.clip_eps, self.clip_eps)
                    surr1 = (value - sb.returnn).pow(2)
                    surr2 = (value_clipped - sb.returnn).pow(2)
                    value_loss = torch.max(surr1, surr2).mean()

                    loss = policy_loss - self.entropy_coef * entropy + self.value_loss_coef * value_loss

                    # Update batch values

                    batch_entropy += entropy.item()
                    batch_value += value.mean().item()
                    batch_policy_loss += policy_loss.item()
                    batch_value_loss += value_loss.item()
                    batch_loss += loss

                    # Update memories for next epoch

                    if self.acmodel.recurrent and i < self.ac_recurrence - 1:
                        exps.ac_memory[inds + i + 1] = memory.detach()

                # Update batch values

                batch_entropy /= self.ac_recurrence
                batch_value /= self.ac_recurrence
                batch_policy_loss /= self.ac_recurrence
                batch_value_loss /= self.ac_recurrence
                batch_loss /= self.ac_recurrence

                # Update actor-critic

                self.ac_optimizer.zero_grad()
                batch_loss.backward()
                grad_norm = sum(p.grad.data.norm(2).item() ** 2 for p in self.acmodel.parameters()) ** 0.5
                torch.nn.utils.clip_grad_norm_(self.acmodel.parameters(), self.max_grad_norm)
                self.ac_optimizer.step()

                # Update log values

                log_entropies.append(batch_entropy)
                log_values.append(batch_value)
                log_policy_losses.append(batch_policy_loss)
                log_value_losses.append(batch_value_loss)
                log_grad_norms.append(grad_norm)

        # Log some values

        logs = {
            "entropy": np.mean(log_entropies),
            "value": np.mean(log_values),
            "policy_loss": np.mean(log_policy_losses),
            "value_loss": np.mean(log_value_losses),
            "ac_grad_norm": np.mean(log_grad_norms)
        }

        return logs


    def update_disc_parameters(self, exps, demos):
        # Collect experiences
        exps_acc = []
        demos_acc = []
        self.discmodel.output_z = True
        self.beta = 0
        for _ in range(self.epochs):
            # Initialize log values
 
            log_losses = []
            log_grad_norms = []

            exps_inds = np.arange(0, len(exps), self.ac_recurrence)
            demos_inds = np.arange(0, len(demos), self.disc_recurrence)

            if True:
                # Initialize batch values
                batch_loss = 0

                # Initialize memory

                if self.discmodel.recurrent:
                    exps_memory = exps.disc_memory[exps_inds]
                    demos_memory = demos.disc_memory[demos_inds]
                for i in range(self.disc_recurrence):
                    # Create a sub-batch of experience
                    exps_sb = exps[exps_inds + i]
                    demos_sb = demos[demos_inds + i]
                    # Compute loss

                    if self.discmodel.recurrent:
                        exps_learner, exps_memory, exps_mu, exps_logvar = self.discmodel(exps_sb.obs, exps_sb.action.to(self.device), exps_memory.to(self.device) * exps_sb.mask.to(self.device))
                        demos_learner, demos_memory, demos_mu, demos_logvar = self.discmodel(demos_sb.obs, demos_sb.action, demos_memory * demos_sb.mask)
                    else:
                        exps_learner, exps_mu, exps_logvar = self.discmodel(exps_sb.obs, exps_sb.action.to(self.device))
                        demos_learner, demos_mu, demos_logvar = self.discmodel(demos_sb.obs, demos_sb.action)
                    #exps_learner = exps_learner.log_prob(exps_sb.action.to(self.device)).exp().reshape(-1, 1)
                    #demos_learner = demos_learner.log_prob(demos_sb.action).exp().reshape(-1, 1)

                    exps_acc.append(exps_learner.mean().detach().item())
                    demos_acc.append(demos_learner.mean().detach().item())
                    
                    exps_kld = kl_divergence(exps_mu, exps_logvar)
                    exps_kld = exps_kld.mean()
                    
                    demos_kld = kl_divergence(demos_mu, demos_logvar)
                    demos_kld = demos_kld.mean()
                    
                    kld = 0.5 * (demos_kld + exps_kld)
                    bottleneck_loss = kld - self.i_c

                    self.beta = max(0, self.beta + self.alpha_beta * bottleneck_loss.detach())

                    criterion = torch.nn.BCELoss()
                    loss = criterion(exps_learner, torch.ones((exps_learner.shape[0], 1)).to(self.device)) + \
                        criterion(demos_learner, torch.zeros((demos_learner.shape[0], 1)).to(self.device)) + \
                            self.beta * bottleneck_loss
                    # Update batch values

                   
                    batch_loss += loss
                    # Update memories for next epoch

                    if self.discmodel.recurrent and i < self.disc_recurrence - 1:
                        exps.disc_memory[exps_inds + i + 1] = exps_memory.detach()
                        demos.disc_memory[demos_inds +i + 1] = demos_memory.detach()

                # Update batch values
 
                batch_loss /= self.disc_recurrence

                # Update actor-critic

                self.disc_optimizer.zero_grad()
                batch_loss.backward()
                grad_norm = sum(p.grad.data.norm(2).item() ** 2 for p in self.discmodel.parameters()) ** 0.5
                torch.nn.utils.clip_grad_norm_(self.discmodel.parameters(), self.max_grad_norm)
                self.disc_optimizer.step()

                # Update log values
 
                log_losses.append(batch_loss.data.detach().cpu().numpy())
                log_grad_norms.append(grad_norm)

        # Log some values

        logs = {
            "exps_acc": np.mean(exps_acc),
            "demos_acc": np.mean(demos_acc),
            "disc_loss": np.mean(log_losses),
            "disc_grad_norm": np.mean(log_grad_norms)
        }
        self.discmodel.output_z = False

        return logs

    def _get_batches_starting_indexes(self, recurrence, num_frames = None, capacity = None):
        """Gives, for each batch, the indexes of the observations given to
        the model and the experiences used to compute the loss at first.

        First, the indexes are the integers from 0 to `self.num_frames` with a step of
        `self.recurrence`, shifted by `self.recurrence//2` one time in two for having
        more diverse batches. Then, the indexes are splited into the different batches.

        Returns
        -------
        batches_starting_indexes : list of list of int
            the indexes of the experiences to be used at first for each batch
        """
        num_frames = self.num_frames if num_frames is None else num_frames
        capacity = self.num_frames_per_proc if capacity is None else capacity
        indexes = np.arange(0, num_frames, recurrence)
        indexes = np.random.permutation(indexes)

        # Shift starting indexes by self.recurrence//2 half the time
        if self.batch_num % 2 == 1:
            indexes = indexes[(indexes + recurrence) % capacity != 0]
            indexes += recurrence // 2
        self.batch_num += 1

        num_indexes = self.batch_size // recurrence
        batches_starting_indexes = [indexes[i:i+num_indexes] for i in range(0, len(indexes), num_indexes)]

        return batches_starting_indexes
