import os
import numpy as np
import torch
import torch.nn.functional as F
from MindVideo import create_Wen_dataset
from MindVideo import fMRIEncoder
import argparse
import datetime
import wandb
import torchvision.transforms as transforms
from einops import rearrange
import copy
import numbers
from omegaconf import OmegaConf
from typing import Dict, Optional
from accelerate import Accelerator
from accelerate.utils import set_seed
import inspect
from diffusers.utils.import_utils import is_xformers_available
from diffusers.optimization import get_scheduler
import math 
from tqdm.auto import tqdm
from accelerate.utils import DistributedDataParallelKwargs,InitProcessGroupKwargs
from datetime import timedelta
from transformers import CLIPProcessor, CLIPModel
from torch.utils.data import Sampler
import nlpaug.augmenter.word as naw
import nlpaug.flow as naf

def channel_last(img):
    if img.shape[-1] == 3:
        return img
    if len(img.shape) == 3:
        img = rearrange(img, 'c h w -> h w c')
    elif len(img.shape) == 4:
        img = rearrange(img, 'f c h w -> f h w c')
    else:
        raise ValueError(f'img shape should be 3 or 4, but got {len(img.shape)}')
    return img

def channel_first(img):
    if len(img.shape) == 3:
        if img.shape[0] == 3:
            return img
        img = rearrange(img, 'h w c -> c h w')
    elif len(img.shape) == 4:
        if img.shape[1] == 3:
            return img
        img = rearrange(img, 'f h w c -> f c h w')
    else:
        raise ValueError(f'img shape should be 3 or 4, but got {len(img.shape)}')
    return img


def normalize(img):
    if img.shape[-1] == 3 and len(img.shape) == 3:
        img = rearrange(img, 'h w c -> c h w')
    elif img.shape[-1] == 3 and len(img.shape) == 4:
        img = rearrange(img, 'f h w c -> f c h w')
    img = torch.tensor(img)
    # img = img * 2.0 - 1.0 # to -1 ~ 1
    return img


def crop(clip, i, j, h, w):
    """
    Args:
        clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
    """
    assert len(clip.size()) == 4, "clip should be a 4D tensor"
    return clip[..., i:i + h, j:j + w]

class RandomCropVideo(transforms.RandomCrop):
    def __init__(self, size):
        if isinstance(size, numbers.Number):
            self.size = (int(size), int(size))
        else:
            self.size = size

    def __call__(self, clip):
        """
        Args:
            clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
        Returns:
            torch.tensor: randomly cropped/resized video clip.
                size is (C, T, OH, OW)
        """
        i, j, h, w = self.get_params(clip, self.size)
        return crop(clip, i, j, h, w)

    def __repr__(self):
        return self.__class__.__name__ + '(size={0})'.format(self.size)

class random_crop:
    def __init__(self, h, w, p):
        self.h = h
        self.w = w
        self.p = p
    def __call__(self, img):
        if torch.rand(1) < self.p:
            return RandomCropVideo(size=(self.h, self.w))(img)
        return img
    
def fmri_transform(x, sparse_rate=0.2):
    # x: 1, num_voxels
    x_aug = copy.deepcopy(x)
    idx = np.random.choice(x.shape[0], int(x.shape[0]*sparse_rate), replace=False)
    x_aug[idx] = 0
    return torch.FloatTensor(x_aug)

def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
    return F.cross_entropy(logits, torch.arange(len(logits), device=logits.device))


def criteria(fmri_embed, text_embed, image_embed, logit_scale, val=False, **kwargs):
    loss = 0.0
    # fmri and image constrastive loss
    logits = torch.matmul(fmri_embed, image_embed.t()) * logit_scale
    img_loss = contrastive_loss(logits)
    loss += img_loss

    # fmri and text constrastive loss
    logits = torch.matmul(fmri_embed, text_embed.t()) * logit_scale
    text_loss = contrastive_loss(logits)
    loss += text_loss
    if val:
        return loss / 2.0, img_loss, text_loss
    return (loss / 2.0)

class ContrastiveSampler(Sampler):
    def __init__(self, data_source, seed=0, shuffle=True):
        self.data_source = data_source
        self.time = data_source.t
        self.video_num = len(data_source) // self.time
        self.rng = np.random.RandomState(seed)
        self.shuffle = shuffle
    def __iter__(self):
        # Create a list of indices
        indices = np.arange(len(self.data_source)).reshape(self.video_num, self.time)
        # Shuffle the indices
        if self.shuffle:
            x_idx = self.rng.permutation(np.arange(self.video_num))
            y_idx = self.rng.permutation(np.arange(self.time))
            indices = indices[x_idx, :]
            indices = indices[:, y_idx]
        indices = indices.transpose(1, 0).reshape(-1)
        # Yield the indices
        for idx in indices:
            yield idx

    def __len__(self):
        return len(self.data_source) 

def main(  
        train_data_setting: Dict, 
        fmri_encoder_path: str='./pretrains/fmri_encoder',
        data_dir: str='./data',
        seed: int=2023,
        dataset: str='Wen',
        patch_size: int=16,
        subjects: list=['subject1'],
    
        gradient_accumulation_steps: int=1,
        mixed_precision: str='fp16',
        random_crop_prob: float=0.5,
        working_dir: str='.',
        cache_dir: str='./.cache',
        resume_from_checkpoint: Optional[str] = None,
        enable_xformers_memory_efficient_attention: bool = True,
        gradient_checkpointing: bool = True,
        learning_rate: float = 5.3e-5,
        adam_beta1: float = 0.9,
        adam_beta2: float = 0.999,
        adam_weight_decay: float = 1e-2,
        adam_epsilon: float = 1e-8,
        train_batch_size: int = 4,
        eval_batch_size: int = 4,
        lr_scheduler: str = "constant",
        lr_warmup_steps: int = 0,
        max_train_steps: int = 500,
        output_path: Optional[str] = None,
        max_grad_norm: float = 1.0,
        checkpointing_steps: int = 500,
        validation_steps: int = 100,
        window_size: int = 3,
        group_name: str = 'default',
        fps: int = 3,
        **kwargs
):  
    *_, config = inspect.getargvalues(inspect.currentframe())
    device = torch.device(f'cuda') if torch.cuda.is_available() else torch.device('cpu')
    set_seed(seed)


    kwargs = [DistributedDataParallelKwargs(find_unused_parameters=True, static_graph=True),
              InitProcessGroupKwargs(timeout=timedelta(minutes=120))]
    accelerator = Accelerator(
        gradient_accumulation_steps=gradient_accumulation_steps,
        mixed_precision=mixed_precision,
        log_with="wandb",
        kwargs_handlers=kwargs,
    )

    if accelerator.is_main_process:
        output_path = os.path.join(working_dir, 'results', 'contrastive_tuning', '%s'%(datetime.datetime.now().strftime("%d-%m-%Y-%H:%M:%S"))) if output_path is None else output_path
        os.makedirs(output_path, exist_ok=True)
        accelerator.init_trackers(
            "fmri-reconst-movie",
            config=config,
            init_kwargs={
            "wandb": {
                "notes": 'this runs multimodal contrastive learning',
                "group": group_name,
                "reinit": True,
                'save_code': True,
                "anonymous": "allow",
                }
            },

        )
        OmegaConf.save(config, os.path.join(output_path, 'config.yaml'))
    else:
        output_path = os.path.join(working_dir, 'results', 'contrastive_tuning') if output_path is None else output_path

    crop_ratio = train_data_setting.crop_ratio
    h = train_data_setting.height
    w = train_data_setting.width
    resize_img_size = train_data_setting.resize_img_size

    # define image transform
    h_crop_pix = int(crop_ratio*h)
    w_crop_pix = int(crop_ratio*w)
    img_transform_train = transforms.Compose([
        normalize,
        random_crop(h-h_crop_pix, w-w_crop_pix, p=random_crop_prob),
        transforms.Resize((resize_img_size, resize_img_size)), 
        channel_first
    ])
    img_transform_test = transforms.Compose([
        normalize, transforms.Resize((resize_img_size, resize_img_size)), 
        channel_first
    ])

    # define text transform
    text_aug = naf.Sometimes([
        naw.SynonymAug(),
        naw.RandomWordAug(action='swap'),
    ], aug_p=0.5)

    if dataset == 'Wen':
        dataset_train, dataset_test = create_Wen_dataset(data_dir, patch_size, 
                fmri_transform=fmri_transform, image_transform=[img_transform_train, img_transform_test], 
                subjects=subjects, window_size=window_size, fps=fps)
        num_voxels = dataset_train.num_voxels
        print('num_voxels: ', num_voxels)
    else:
        raise NotImplementedError(f'{dataset} not implemented')
    
    fmri_encoder = fMRIEncoder.from_pretrained(fmri_encoder_path, num_voxels=num_voxels)
    clip_model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14", cache_dir=cache_dir)
    clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14", cache_dir=cache_dir)
    
    clip_model.requires_grad_(False)

    if enable_xformers_memory_efficient_attention:
        if is_xformers_available():
            fmri_encoder.enable_xformers_memory_efficient_attention()
        else:
            raise ValueError("xformers is not available. Make sure it is installed correctly")

    if gradient_checkpointing:
        fmri_encoder.enable_gradient_checkpointing()

    optimizer = torch.optim.AdamW(
        list(fmri_encoder.parameters()),
        lr=learning_rate,
        betas=(adam_beta1, adam_beta2),
        weight_decay=adam_weight_decay,
        eps=adam_epsilon,
    )
    if accelerator.is_main_process:
        wandb.watch(fmri_encoder, log="all", log_freq=500)

    sampler_train = ContrastiveSampler(dataset_train, seed=seed, shuffle=True)
    sampler_test = ContrastiveSampler(dataset_test, seed=seed, shuffle=False)
    # DataLoaders creation:
    train_dataloader = torch.utils.data.DataLoader(
        dataset_train, batch_size=train_batch_size, sampler=sampler_train
    )
    eval_dataloader = torch.utils.data.DataLoader(
        dataset_test, batch_size=eval_batch_size, sampler=sampler_test
    )

    # Scheduler
    lr_scheduler = get_scheduler(
        lr_scheduler,
        optimizer=optimizer,
        num_warmup_steps=lr_warmup_steps * gradient_accumulation_steps,
        num_training_steps=max_train_steps * gradient_accumulation_steps,
    )

    # Prepare everything with our `accelerator`.
    fmri_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
        fmri_encoder, optimizer, train_dataloader, lr_scheduler
    )
    # For mixed precision training we cast the text_encoder and vae weights to half-precision
    # as these models are only used for inference, keeping weights in full precision is not required.
    weight_dtype = torch.float32
    if accelerator.mixed_precision == "fp16":
        weight_dtype = torch.float16
    elif accelerator.mixed_precision == "bf16":
        weight_dtype = torch.bfloat16

    clip_model.to(accelerator.device, dtype=weight_dtype)
    # clip_processor.to(accelerator.device, dtype=weight_dtype)

    # We need to recalculate our total training steps as the size of the training dataloader may have changed.
    num_update_steps_per_epoch = math.ceil(len(train_dataloader) / gradient_accumulation_steps)
    # Afterwards we recalculate our number of training epochs
    num_train_epochs = math.ceil(max_train_steps / num_update_steps_per_epoch)

    # Train!
    total_batch_size = train_batch_size * accelerator.num_processes * gradient_accumulation_steps
    print("***** Running training *****")
    print(f"  Num examples = {len(dataset_train)}")
    print(f"  Num Epochs = {num_train_epochs}")
    print(f"  Instantaneous batch size per device = {train_batch_size}")
    print(f"  Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
    print(f"  Gradient Accumulation steps = {gradient_accumulation_steps}")
    print(f"  Total optimization steps = {max_train_steps}")
    global_step = 0
    first_epoch = 0   

    # Potentially load in the weights and states from a previous save
    if resume_from_checkpoint:
        if resume_from_checkpoint != "latest":
            path = os.path.basename(resume_from_checkpoint)
        else:
            # Get the most recent checkpoint
            dirs = os.listdir(output_path)
            dirs = [d for d in dirs if d.startswith("checkpoint")]
            dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
            path = dirs[-1]
        accelerator.print(f"Resuming from checkpoint {path}")
        accelerator.load_state(os.path.join(output_path, path))
        global_step = int(path.split("-")[1])
        first_epoch = global_step // num_update_steps_per_epoch
        resume_step = global_step % num_update_steps_per_epoch
    
    # Only show the progress bar once on each machine.
    progress_bar = tqdm(range(global_step, int(max_train_steps)), disable=not accelerator.is_local_main_process)
    progress_bar.set_description("Steps")
    val_loss_min = 1000
    for epoch in range(first_epoch, num_train_epochs):
        train_loss = 0.0
        train_loss_list = []
        for step, batch in enumerate(train_dataloader):
            fmri_encoder.train()
            # Skip steps until we reach the resumed step
            if resume_from_checkpoint and epoch == first_epoch and step < resume_step:
                if step % gradient_accumulation_steps == 0:
                    progress_bar.update(1)
                continue
            with accelerator.accumulate(fmri_encoder):
                frame_idx = np.random.choice(dataset_train.fpf, 1)[0]
                pixel_values = [img for img in batch["image"][:, frame_idx, ...]]
                text = [t for t in batch["text"][frame_idx]] # wired behaivour when put text in dataset
                text = text_aug.augment(text, n=len(text))
                with torch.no_grad():
                    inputs = clip_processor(text=text, images=pixel_values, return_tensors="pt", padding=True)
                    outputs = clip_model(pixel_values=inputs.pixel_values.to(accelerator.device, weight_dtype), 
                                        input_ids=inputs.input_ids.to(accelerator.device))
                text_embed = outputs.text_embeds.to(torch.float32)  # cast back to full precision
                image_embed = outputs.image_embeds.to(torch.float32) # cast back to full precision
                fmri_embed = fmri_encoder(batch["fmri"]).mean(dim=1) # n, hidden_dim (77), embed_dim -> n, embed_dim
                fmri_embed = fmri_embed / fmri_embed.norm(p=2, dim=-1, keepdim=True)

                logit_scale = fmri_encoder.logit_scale.exp()
                loss = criteria(fmri_embed, text_embed, image_embed, logit_scale)
                # Gather the losses across all processes for logging (if we use distributed training).
                avg_loss = accelerator.gather(loss.repeat(train_batch_size)).mean()
                train_loss += avg_loss.item() / gradient_accumulation_steps
                # Backpropagate
                accelerator.backward(loss)
                if accelerator.sync_gradients:
                    accelerator.clip_grad_norm_(list(fmri_encoder.parameters()), max_grad_norm)
                optimizer.step()
                lr_scheduler.step()
                optimizer.zero_grad()

                # Checks if the accelerator has performed an optimization step behind the scenes
            if accelerator.sync_gradients:
                progress_bar.update(1)
                global_step += 1
                train_loss_list.append(train_loss)
                # accelerator.log({"train_loss": train_loss}, step=global_step)
                train_loss = 0.0

                if global_step % validation_steps == 0:
                    if accelerator.is_main_process:
                        with torch.no_grad():
                            fmri_encoder.eval()
                            loss_val_list = []
                            img_loss_val_list = []
                            text_loss_val_list = []
                            for idx, prompt in enumerate(eval_dataloader):
                                frame_idx = np.random.choice(dataset_test.fpf, 1)[0]
                                pixel_values = [img for img in prompt["image"][:, frame_idx, ...]]
                                text = [t for t in prompt["text"][frame_idx]] 
                                inputs = clip_processor(text=text, images=pixel_values, return_tensors="pt", padding=True)
                                outputs = clip_model(pixel_values=inputs.pixel_values.to(accelerator.device, weight_dtype), 
                                                    input_ids=inputs.input_ids.to(accelerator.device))
                                text_embed = outputs.text_embeds.to(torch.float32)  # cast back to full precision
                                image_embed = outputs.image_embeds.to(torch.float32) # cast back to full precision
                                fmri_embed = fmri_encoder(prompt["fmri"].to(accelerator.device)).mean(dim=1) 
                                fmri_embed = fmri_embed / fmri_embed.norm(p=2, dim=-1, keepdim=True)
                                logit_scale = fmri_encoder.logit_scale.exp()
                                loss_val, img_loss, text_loss = criteria(fmri_embed, text_embed, image_embed, logit_scale, val=True)
                                img_loss_val_list.append(img_loss.item())
                                text_loss_val_list.append(text_loss.item())
                                loss_val_list.append(loss_val.item())
                                
                            accelerator.log({"val_loss": np.mean(loss_val_list), 
                                            "img_loss": np.mean(img_loss_val_list), 
                                            "text_loss": np.mean(text_loss_val_list)})
                            if np.mean(loss_val_list) < val_loss_min:
                                save_path = os.path.join(output_path, f"checkpoint-best")
                                accelerator.save_state(save_path)
                                print(f"Saved state to {save_path}")
                                val_loss_min = np.mean(loss_val_list)
                                print(f"val_loss_min: {val_loss_min}")

            logs = {"step_loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0], 'logit_scale': fmri_encoder.logit_scale.exp().detach().item()}
            progress_bar.set_postfix(**logs)

            if global_step >= max_train_steps:
                break
        accelerator.log({"train_loss": np.mean(train_loss_list)})
        accelerator.log({"step": global_step})
        accelerator.log({"epoch": epoch})

    accelerator.wait_for_everyone()
    if accelerator.is_main_process:
        save_path = os.path.join(output_path, f"checkpoint-final")
        accelerator.save_state(save_path)
        print(f"Saved state to {save_path}")

    accelerator.end_training()
    

def get_args_parser():
    parser = argparse.ArgumentParser('Decoding fMRI to reconstruct videos')
    # project parameters
    parser.add_argument('--config', type=str, default='configs/contrastive_tuning.yaml', help='path to config file')
    return parser

if __name__ == '__main__':
    args = get_args_parser()
    args = args.parse_args()
    config = OmegaConf.load(args.config)
    config.config_path = args.config

    main(**config)