"""
The MIT License (MIT) Copyright (c) 2020 Andrej Karpathy

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from xmlrpc.client import boolean
import random
import numpy as np
import copy
import torch
import torch.nn as nn
from torch.nn import functional as F
import pdb
from mingpt.leap_model_babyai import token2idx

AGENT_ID = 10
AGENT_COLOR = 6


def set_seed(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)

def top_k_logits(logits, k):
    v, ix = torch.topk(logits, k)
    out = logits.clone()
    out[out < v[:, [-1]]] = -float('Inf')
    return out

@torch.no_grad()
def leap_sample_multi_step(leap_model, x, timesteps=None, insts=None, full_obs=None, logger=None, sample_iteration=1, stuck_action=-1):
    """
    take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
    the sequence, feeding the predictions back into the model each time. Clearly the sampling
    has quadratic complexity unlike an RNN that is only linear, and has a finite context window
    of block_size, unlike an RNN that has an infinite context window.
    """
    leap_model.eval()
    rate = leap_model.rate
    block_size = leap_model.block_size
    batch_size = x.shape[0]
    context = block_size // rate

    sampled_actions = []

    cur_timestep = timesteps.cpu().numpy()[0,0,0]
    horizon = context #5 #random.randint(3, 6)
    cur_timestep += horizon
    timesteps=((cur_timestep) * torch.ones((1, 1, 1), dtype=torch.int64).to('cuda'))

    init_states = torch.clone(x[:, -1]).unsqueeze(1)

    goals = torch.clone(x[:, -1, -2:]).cpu().to(dtype=torch.float32)
    goals = torch.repeat_interleave(torch.Tensor(goals).unsqueeze(1), horizon - 1, dim=1).to(dtype=torch.long).to('cuda')

    sample_states = [[0,0,0] for _ in range(horizon - 1)]
    sample_states = torch.repeat_interleave(torch.Tensor(sample_states).unsqueeze(0), batch_size, dim=0).to('cuda') 

    if (context > 1):
        sample_states = torch.cat((sample_states, goals), dim=2)
        sample_states = torch.cat((init_states, sample_states), dim=1).to(dtype=torch.long)
    elif (context == 1):
        sample_states = init_states

    init_obss = torch.clone(full_obs[:,-1]).cpu()
    sample_obss = torch.repeat_interleave(torch.Tensor(init_obss).unsqueeze(1), horizon, dim=1).to(dtype=torch.float32).to('cuda')

    sample_actions = [[token2idx('<-MASK->')] for i in range(context)]
    sample_actions = torch.repeat_interleave(torch.Tensor(sample_actions).unsqueeze(0), batch_size, dim=0).to(dtype=torch.long).to('cuda')
    
    
    init_temperature = 0.5
    energys = []
    # MCMC construct sample trajectory
    for i in range(sample_iteration):
        if (i==0):
            action_masks = np.ones((batch_size, context, 1)).astype(boolean)
            action_masks = torch.from_numpy(action_masks).to('cuda')
        else:
            #temperature = min(init_temperature + i / (2*sample_iteration), 0.9) if i > 0 else 0
            action_masks = np.zeros((batch_size, context, 1)).astype(boolean)
            #np.random.uniform(0, 1, (batch_size, context, 1)) >= temperature
            msk = random.randint(0, context-1)
            action_masks[0,msk,0] = True
            #np.random.uniform(0, 1, (batch_size, context, 1)) >= temperature
            action_masks = torch.from_numpy(action_masks).to('cuda')
            # MCMC problem may come from this part NAZA
            # action correct rate problem come from this part
            # it seems that it doesn't matter ...
            # so what make the action correct rate increase a lot??
            #action_masks = torch.logical_and(action_masks, target_action_masks)

        sample_actions[action_masks] = token2idx('<-MASK->')
        action_logits = leap_model.forward(sample_states, sample_actions, timesteps=timesteps, insts=insts, full_image=sample_obss, mode='eval')
        if (stuck_action != -1):
            action_logits[0,0,stuck_action] = np.float("-inf")
        #action_val = torch.multinomial(F.softmax(action_logits.reshape(-1,action_logits.shape[2]), dim=-1), num_samples=1).reshape(self.batch_size,context)
        _, action_val = torch.topk(F.softmax(action_logits.reshape(-1,action_logits.shape[2]), dim=-1), k=1, dim=-1)
        action_val = action_val.reshape(batch_size, context)
        if (i < sample_iteration-1):
            sample_actions[action_masks] = action_val.unsqueeze(2)[action_masks]
            #iter_actions = sample_actions.cpu().numpy()
            #sample_states, sample_obss = leap_model.update_samples(sample_states, sample_obss, iter_actions)
            #energys.append(self.compute_energy(target_actions, sample_actions, action_logits, torch.logical_and(action_masks, target_action_masks)).item())
        else:
            train_sample_actions = sample_actions.clone()
            train_sample_actions[action_masks] = action_val.unsqueeze(2)[action_masks]
            #sample_actions[action_masks] = action_val.unsqueeze(2)[action_masks]
            #iter_actions = train_sample_actions.cpu().numpy()
            #sample_states = self.update_sample_states(sample_states, iter_actions)
            #energys.append(self.compute_energy(target_actions, train_sample_actions, action_logits, torch.logical_and(action_masks, target_action_masks)).item())
    leap_model.train()
    #if (stuck_action != -1):
    #    pdb.set_trace()
    #sampled_actions = [action for action in sample_actions[0,-horizon:,0]]
    return train_sample_actions.flatten().cpu().tolist()



@torch.no_grad()
def random_shooting(leap_model, x, timesteps=None, insts=None, full_obs=None, logger=None, sample_iteration=1, stuck_action=-1):
    """
    take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
    the sequence, feeding the predictions back into the model each time. Clearly the sampling
    has quadratic complexity unlike an RNN that is only linear, and has a finite context window
    of block_size, unlike an RNN that has an infinite context window.
    """
    leap_model.eval()
    rate = leap_model.rate
    block_size = leap_model.block_size
    batch_size = x.shape[0]
    context = block_size // rate
    sampled_actions = []
    cur_timestep = timesteps.cpu().numpy()[0,0,0]
    horizon = context #5 #random.randint(3, 6)
    cur_timestep += horizon
    timesteps=((cur_timestep) * torch.ones((1, 1, 1), dtype=torch.int64).to('cuda'))
    init_states = torch.clone(x[:, -1]).unsqueeze(1)

    goals = torch.clone(x[:, -1, -2:]).cpu().to(dtype=torch.float32)
    goals = torch.repeat_interleave(torch.Tensor(goals).unsqueeze(1), horizon - 1, dim=1).to(dtype=torch.long).to('cuda')

    sample_states = [[0,0,0] for _ in range(horizon - 1)]
    sample_states = torch.repeat_interleave(torch.Tensor(sample_states).unsqueeze(0), batch_size, dim=0).to('cuda') 

    if (context > 1):
        sample_states = torch.cat((sample_states, goals), dim=2)
        sample_states = torch.cat((init_states, sample_states), dim=1).to(dtype=torch.long)
    elif (context == 1):
        sample_states = init_states

    init_obss = torch.clone(full_obs[:,-1]).cpu()
    sample_obss = torch.repeat_interleave(torch.Tensor(init_obss).unsqueeze(1), horizon, dim=1).to(dtype=torch.float32).to('cuda')
    # MCMC construct sample trajectory
    action_masks = np.ones((batch_size, context, 1)).astype(boolean)
    action_masks = torch.from_numpy(action_masks).to('cuda')
    random_shooting_energies = {}
    for i in range(sample_iteration):
        sample_actions = [[random.randint(0, 5)] for _ in range(context)]
        sample_actions = torch.repeat_interleave(torch.Tensor(sample_actions).unsqueeze(0), batch_size, dim=0).to(dtype=torch.long).to('cuda')
        traj_energy = leap_model.gt_trajectory_energy(sample_states, sample_obss, timesteps, insts, target_actions=sample_actions, target_action_masks=action_masks)
        random_shooting_energies[str(i)] = (sample_actions.flatten().cpu().tolist(), traj_energy)
    leap_model.train()
    lowest_energy_actions = sorted(random_shooting_energies.items(), key=lambda item: item[1][1])[0]
    return lowest_energy_actions[1][0]


@torch.no_grad()
def cross_entropy(leap_model, x, timesteps=None, insts=None, full_obs=None, logger=None, sample_iteration=1, stuck_action=-1):
    """
    take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
    the sequence, feeding the predictions back into the model each time. Clearly the sampling
    has quadratic complexity unlike an RNN that is only linear, and has a finite context window
    of block_size, unlike an RNN that has an infinite context window.
    """
    leap_model.eval()
    rate = leap_model.rate
    block_size = leap_model.block_size
    batch_size = x.shape[0]
    context = block_size // rate
    sampled_actions = []
    cur_timestep = timesteps.cpu().numpy()[0,0,0]
    horizon = context #5 #random.randint(3, 6)
    cur_timestep += horizon
    timesteps=((cur_timestep) * torch.ones((1, 1, 1), dtype=torch.int64).to('cuda'))
    init_states = torch.clone(x[:, -1]).unsqueeze(1)
    
    goals = torch.clone(x[:, -1, -2:]).cpu().to(dtype=torch.float32)
    goals = torch.repeat_interleave(torch.Tensor(goals).unsqueeze(1), horizon - 1, dim=1).to(dtype=torch.long).to('cuda')

    sample_states = [[0,0,0] for _ in range(horizon - 1)]
    sample_states = torch.repeat_interleave(torch.Tensor(sample_states).unsqueeze(0), batch_size, dim=0).to('cuda') 

    if (context > 1):
        sample_states = torch.cat((sample_states, goals), dim=2)
        sample_states = torch.cat((init_states, sample_states), dim=1).to(dtype=torch.long)
    elif (context == 1):
        sample_states = init_states

    init_obss = torch.clone(full_obs[:,-1]).cpu()
    sample_obss = torch.repeat_interleave(torch.Tensor(init_obss).unsqueeze(1), horizon, dim=1).to(dtype=torch.float32).to('cuda')
    # MCMC construct sample trajectory
    action_masks = np.ones((batch_size, context, 1)).astype(boolean)
    action_masks = torch.from_numpy(action_masks).to('cuda')
    cem_energies = {}
    num_trajectories = 30
    for j in range(num_trajectories):
        sample_actions = [random.randint(0, 5) for _ in range(context)]
        cem_energies[str(j)] = [sample_actions, 0]
    for i in range(sample_iteration):
        for k, (sample_actions, _) in cem_energies.items():
            sample_actions = torch.repeat_interleave(torch.Tensor(sample_actions).unsqueeze(1).unsqueeze(0), batch_size, dim=1).to(dtype=torch.long).to('cuda')
            traj_energy = leap_model.gt_trajectory_energy(sample_states, sample_obss, timesteps, insts, target_actions=sample_actions, target_action_masks=action_masks)
            cem_energies[k][1] = traj_energy
        sorted_cem = sorted(cem_energies.items(), key=lambda item: item[1][1])[:3]
        cem_energies = {}
        count = 0
        for trajs in sorted_cem:
            actions, energy = trajs[1]
            cem_energies[str(count)] = [actions, 0]
            count += 1
            for j in range(9):
                new_actions = copy.deepcopy(actions)
                new_actions[random.randint(0, context-1)] = random.randint(0, 5)
                cem_energies[str(count)] = [new_actions, 0]
                count += 1
    leap_model.train()
    lowest_energy_actions = sorted(cem_energies.items(), key=lambda item: item[1][1])[0]
    return lowest_energy_actions[1][0]