import itertools
import time

import numpy as np
import torch

from tqdm import trange


class Trainer:
    def __init__(self, model, optimizer, dataloader, loss_fn, device, scheduler=None, eval_fns=None):
        self.model = model
        self.optimizer = optimizer
        self.dataloader = dataloader
        self.loss_fn = loss_fn
        self.device = device
        self.scheduler = scheduler
        self.eval_fns = [] if eval_fns is None else eval_fns
        self.diagnostics = dict()

        self.start_time = time.time()

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

        train_losses = []
        logs = dict()

        train_start = time.time()

        self.model.train()

        # create dataloader-iterator
        data_iter = iter(self.dataloader)

        # iterate over dataset https://stackoverflow.com/a/58876890
        for i in trange(num_steps):
            try:
                data = next(data_iter)
            except StopIteration:
                # StopIteration is thrown if dataset ends
                # reinitialize data loader
                data_iter = iter(self.dataloader)
                data = next(data_iter)

            data = tuple(d.to(self.device) for d in data)
            train_loss = self.train_step(data)
            train_losses.append(train_loss)
            if self.scheduler is not None:
                self.scheduler.step()

        logs["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"evaluation/{k}"] = v

        # add mean success rate to logs
        success_logs = dict(filter(lambda x: "success_rate" in x[0], logs.items()))
        # group by target_rew
        keyfunc = lambda x: x[0].split("/")[2]
        data = sorted(success_logs.items(), key=keyfunc)
        for k, g in itertools.groupby(data, keyfunc):
            # get mean success rate for each target_rew
            mean_success = np.array([e[1] for e in list(g)]).mean()
            logs[f"evaluation/all_tasks/{k}/mean_success_rate"] = mean_success

        logs["time/total"] = time.time() - self.start_time
        logs["time/evaluation"] = time.time() - eval_start
        logs["training/train_loss_mean"] = np.mean(train_losses)
        logs["training/train_loss_std"] = np.std(train_losses)

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

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

        return logs

    def train_step(self, data):
        states, actions, rewards, dones, attention_mask, returns = data
        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()
