import numpy as np
import torch

import time


class Trainer:

    def __init__(self, model, optimizer, batch_size, get_batch_e,get_batch_o, loss_fn,train_type='mean',use_weighted_sum = True, scheduler=None, eval_fns=None):
        self.model = model
        self.optimizer = optimizer
        self.batch_size = batch_size
        self.get_batch_e = get_batch_e
        self.get_batch_o = get_batch_o
        self.loss_fn = loss_fn
        self.scheduler = scheduler
        self.use_weighted_sum = use_weighted_sum
        self.eval_fns = [] if eval_fns is None else eval_fns
        self.diagnostics = dict()
        self.train_type = train_type
        self.start_time = time.time()

    def train_iteration(self, num_steps, iter_num=0, print_logs=False):

        train_losses = []
        e_ = []
        o_ = []
        diff_ = []
        logs = dict()

        train_start = time.time()

        self.model.train()
        for _ in range(num_steps): #num_steps
            train_loss,e,o,diff = self.train_step() 
            train_losses.append(train_loss)
            e_.append(e)
            o_.append(o)
            diff_.append(diff)
            if self.scheduler is not None:
                self.scheduler.step()

        logs['ICRL_time/training'] = time.time() - train_start

        eval_start = time.time()

        self.model.eval()
        for eval_fn in self.eval_fns:
            outputs = eval_fn(self.model)
            for k, v in outputs.items():
                logs[f'ICRL_evaluation/{k}'] = v

        logs['ICRL_time/total'] = time.time() - self.start_time
        logs['ICRL_time/evaluation'] = time.time() - eval_start
        logs['ICRL_training/train_loss_mean'] = np.mean(train_losses)
        logs['ICRL_training/train_loss_std'] = np.std(train_losses)
        logs['ICRL_training/train_expert_pre'] = np.mean(e_)
        logs['ICRL_training/train_obs_pre'] = np.mean(o_)
        logs['ICRL_training/train_diff'] = np.mean(diff_)

        for k in self.diagnostics:
            logs[k] = self.diagnostics[k]

        if print_logs:
            print('=' * 80)
            print(f'ICRL_Iteration {iter_num}')
            # for k, v in logs.items():
            #     print(f'{k}: {v}')

        return logs

    def train_step(self):
        states, actions, rewards, dones, attention_mask, returns = self.get_batch(self.batch_size) #s, a, r, d, rtg, timesteps, mask
        state_target, action_target, reward_target = torch.clone(states), torch.clone(actions), torch.clone(rewards)

        state_preds, action_preds, reward_preds = self.model.forward(
            states, actions, rewards, masks=None, attention_mask=attention_mask, target_return=returns,
        )

        # note: currently indexing & masking is not fully correct
        loss = self.loss_fn(
            state_preds, action_preds, reward_preds,
            state_target[:,1:], action_target, reward_target[:,1:],
        )
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        return loss.detach().cpu().item()
