import os
import torch
import numpy as np

from tqdm.auto import tqdm
from torch.utils.data import Dataset

from Utils.model_utils import normalize_to_neg_one_to_one, unnormalize_to_zero_to_one
from Utils.masking_utils import noise_mask
from diffusion_crf import TimeSeries
from typing import Optional, Mapping, Tuple, List, Sequence, Union, Any, Callable, Dict, Iterator
from jaxtyping import Array, PRNGKeyArray, PyTree, Scalar


def get_sine_dataset(config: dict,
                       args=None,
                       key: Optional[PRNGKeyArray] = None,
                       train_val_test_split: Optional[Tuple[int, int, int]] = None,
                       return_raw_data: bool = False):
    from Utils.io_utils import instantiate_from_config
    dataset = instantiate_from_config(config['old_dataloader'], args=args)
    data = dataset.data

    # Create timeseries objects out of data
    import jax.numpy as jnp
    import jax
    from Utils.Data_utils.my_datasets import make_series
    data_series = jax.vmap(make_series)(data)

    if return_raw_data:
        return data_series

    if train_val_test_split is not None:
        total_size = data_series.batch_size
        train_proportion, val_proportion, test_proportion = train_val_test_split

        n_train = int(total_size * train_proportion)
        n_val = int(total_size * val_proportion)
        n_test = total_size - n_train - n_val  # Ensure all data is used

        # Shuffle the data
        idx = jax.random.permutation(key, jnp.arange(data_series.batch_size))
        data_series = data_series[idx]

        train_series = data_series[:n_train]
        val_series = data_series[n_train:n_train + n_val]
        test_series = data_series[n_train + n_val:]

        return train_series, val_series, test_series

    return data_series

class SineDataset(Dataset):
    def __init__(
        self,
        window=128,
        num=30000,
        dim=12,
        save2npy=True,
        neg_one_to_one=True,
        seed=123,
        period='train',
        output_dir='./OUTPUT',
        predict_length=None,
        missing_ratio=None,
        style='separate',
        distribution='geometric',
        mean_mask_length=3,
        use_pendulum=False,
        args=None
    ):
        super(SineDataset, self).__init__()
        assert period in ['train', 'test'], 'period must be train or test.'
        if period == 'train':
            assert ~(predict_length is not None or missing_ratio is not None), ''

        self.pred_len, self.missing_ratio = predict_length, missing_ratio
        self.style, self.distribution, self.mean_mask_length = style, distribution, mean_mask_length

        self.dir = os.path.join(output_dir, 'samples')
        os.makedirs(self.dir, exist_ok=True)

        if use_pendulum:
            from Data.pendulum.double_pendulum import get_raw_pendulum_data
            self.rawdata = get_raw_pendulum_data(num_samples=num)
        else:

            self.rawdata = self.sine_data_generation(no=num, seq_len=window, dim=dim, save2npy=save2npy,
                                                    seed=seed, dir=self.dir, period=period)
        self.auto_norm = neg_one_to_one
        self.samples = self.normalize(self.rawdata)
        self.var_num = dim
        self.sample_num = self.samples.shape[0]
        self.window = window

        self.period, self.save2npy = period, save2npy
        if period == 'test':
            if missing_ratio is not None:
                self.masking = self.mask_data(seed)
            elif predict_length is not None:
                masks = np.ones(self.samples.shape)
                masks[:, -predict_length:, :] = 0
                self.masking = masks.astype(bool)
            else:
                raise NotImplementedError()

    @property
    def data(self):
        return self.rawdata

    def normalize(self, rawdata):
        if self.auto_norm:
            data = normalize_to_neg_one_to_one(rawdata)
        return data

    def unnormalize(self, data):
        if self.auto_norm:
            data = unnormalize_to_zero_to_one(data)
        return data

    @staticmethod
    def sine_data_generation(no, seq_len, dim, save2npy=True, seed=123, dir="./", period='train'):
        """Sine data generation.

        Args:
           - no: the number of samples
           - seq_len: sequence length of the time-series
           - dim: feature dimensions

        Returns:
           - data: generated data
        """
        # Store the state of the RNG to restore later.
        st0 = np.random.get_state()
        np.random.seed(seed)

        # Initialize the output
        data = list()
        # Generate sine data
        for i in tqdm(range(0, no), total=no, desc="Sampling sine-dataset"):
            # Initialize each time-series
            temp = list()
            # For each feature
            for k in range(dim):
                # Randomly drawn frequency and phase
                freq = np.random.uniform(0, 0.1)
                phase = np.random.uniform(0, 0.1)

                # Generate sine signal based on the drawn frequency and phase
                temp_data = [np.sin(freq * j + phase) for j in range(seq_len)]
                temp.append(temp_data)

            # Align row/column
            temp = np.transpose(np.asarray(temp))
            # Normalize to [0,1]
            temp = (temp + 1)*0.5
            # Stack the generated data
            data.append(temp)

        # Restore RNG.
        np.random.set_state(st0)
        data = np.array(data)
        if save2npy:
            np.save(os.path.join(dir, f"sine_ground_truth_{seq_len}_{period}.npy"), data)

        return data

    def mask_data(self, seed=2023):
        masks = np.ones_like(self.samples)
        # Store the state of the RNG to restore later.
        st0 = np.random.get_state()
        np.random.seed(seed)

        for idx in range(self.samples.shape[0]):
            x = self.samples[idx, :, :]  # (seq_length, feat_dim) array
            mask = noise_mask(x, self.missing_ratio, self.mean_mask_length, self.style,
                              self.distribution)  # (seq_length, feat_dim) boolean array
            masks[idx, :, :] = mask

        if self.save2npy:
            np.save(os.path.join(self.dir, f"sine_masking_{self.window}.npy"), masks)

        # Restore RNG.
        np.random.set_state(st0)
        return masks.astype(bool)

    def __getitem__(self, ind):
        if self.period == 'test':
            x = self.samples[ind, :, :]  # (seq_length, feat_dim) array
            m = self.masking[ind, :, :]  # (seq_length, feat_dim) boolean array
            return torch.from_numpy(x).float(), torch.from_numpy(m)
        x = self.samples[ind, :, :]  # (seq_length, feat_dim) array
        return torch.from_numpy(x).float()

    def __len__(self):
        return self.sample_num


if __name__ == '__main__':
    import matplotlib.pyplot as plt
    from debug import *
    import tqdm
    from diffusion_crf import *
    from Models.experiment_identifier import ExperimentIdentifier

    # Load the dataset
    eid = ExperimentIdentifier.make_experiment_id(config_name='sines',
                                                  objective='ml',
                                                  model_name='my_non_probabilistic',
                                                  sde_type='brownian',
                                                  freq=0,
                                                  group='asdf',
                                                  seed=0)
    config = eid.create_config()
    datasets = eid.get_data()
    train_data, val_data, test_data = datasets['train_data'], datasets['val_data'], datasets['test_data']
    idx = 0
    data_series = train_data[idx]

    # Create the SDE
    key = random.PRNGKey(0)
    y_dim = data_series.yts.shape[-1]
    freq = 0
    sde_type = 'brownian'


    def to_latent(noise_std: float, latent_sigma: float, data_series: TimeSeries, key: PRNGKeyArray):
        sde = BrownianMotion(sigma=noise_std, dim=y_dim)
        encoder = PaddingLatentVariableEncoderWithPrior(y_dim=y_dim,
                                                    x_dim=sde.dim,
                                                    sigma=latent_sigma)
        prob_series = encoder(data_series)
        conditioned_sde = ConditionedLinearSDE(sde, prob_series)
        sampled_series = conditioned_sde.sample(key, data_series.ts)
        return sampled_series

    obs_sigmas = [0.001]
    # latent_sigmas = jnp.logspace(-4, -2, 7, base=10)
    latent_sigmas = [0.0001]
    all_series = [data_series]
    titles = ['Original']
    for noise_std in obs_sigmas:
        for latent_sigma in latent_sigmas:
            sampled_series = to_latent(noise_std, latent_sigma, data_series, key)
            all_series.append(sampled_series)
            print(f'o={noise_std}, l={latent_sigma}')
            titles.append(f'o={noise_std:.2f}, l={latent_sigma:.2f}')



    TimeSeries.plot_multiple_series(all_series,
                                    titles=titles,
                                    marker_size=3,
                                    width_per_series=3,
                                    height_per_dim=1.5)

    latent_sigma = 0.0001
    noise_std = 0.001
    keys = random.split(key, train_data.batch_size)
    out = jax.vmap(partial(to_latent, noise_std, latent_sigma))(train_data, keys)
    assert not jnp.isnan(out.yts).any()


    import pdb; pdb.set_trace()