import os.path
import sys

from Utils import environments
import gym
import d4rl
import time
import datetime
import torch
import itertools
import numpy as np
from loguru import logger

import argparse

from diffusion_predictor.Predictor_config import DMBP_config, update_DMBP_config
from diffusion_predictor.Predictor_net import Diffusion_instance
from diffusion_predictor.render_img import MuJoCoRenderer
from Utils.Batch_Buffer import batch_buffer
from Utils.seed import setup_seed, seed_env

def train_DMBP(args):
    env_name, dataset_name, seed = args.env_name, args.dataset, args.seed

    config = update_DMBP_config(env_name, DMBP_config, args)

    device = torch.device(args.device)
    setup_seed(seed)
    
    Buffer = batch_buffer(config, env_name, dataset_name, device, buffer_mode='normal', buffer_normalization=False)
    detector = Diffusion_instance(Buffer.obs_dim, Buffer.act_dim, device, config, "naive")
    denoiser = Diffusion_instance(Buffer.obs_dim, Buffer.act_dim, device, config, "naive")

    if config["load_model_path"] == "nothing":
        Training_steps_per_epoch = config["steps_per_epoch"]
        Epoches = config["total_epoch"]
        for steps_k in range(Epoches):
            if steps_k <= config["detector_training_loops"]:
                detector.train(Buffer, Training_steps_per_epoch, config['batch_size'], None, 0.1)
            denoiser.train(Buffer, Training_steps_per_epoch, config['batch_size'], detector, 0.5)
            if config["debug"] == True:
                Buffer.simple_detect(denoiser, detector)
            detector.save_model(f"models_cp/{env_name}_{dataset_name}_detector.pkl")
            denoiser.save_model(f"models_cp/{env_name}_{dataset_name}_denoiser.pkl")
    else:
        model_path = config["load_model_path"]
        dataset_name = config["dataset"]
        detector.load_model(f"{model_path}_detector.pkl")
        denoiser.load_model(f"{model_path}_denoiser.pkl")
    
    Buffer.get_dataset(denoiser, detector, f"datasets_cp/{env_name}_{dataset_name}_{args.dn_stp}", 0.7)
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--env_name', default='hopper', type=str)
    parser.add_argument('--dataset', default='medium-expert', type=str)
    parser.add_argument('--device', default="cuda:0", type=str)

    parser.add_argument('--seed', default=0, type=int)
    parser.add_argument('--load_model_path', default="nothing", type=str)
    parser.add_argument('--debug', default=False, type=bool)

    parser.add_argument('--detector_training_loops', default=10000, type=int)

    parser.add_argument('--dataset_path', default=None, type=str)
    parser.add_argument('--dn_stp', default=100, type=int)

    args = parser.parse_args()

    train_DMBP(args)