import os
import pickle
import random

import numpy as np
import torch

from dassl.data.datasets import DATASET_REGISTRY, Datum, DatasetBase
from dassl.utils import mkdir_if_missing

from .oxford_pets import OxfordPets
from .dtd import DescribableTextures as DTD
from collections import defaultdict

NEW_CNAMES = {
    "AnnualCrop": "Annual Crop Land",
    "Forest": "Forest",
    "HerbaceousVegetation": "Herbaceous Vegetation Land",
    "Highway": "Highway or Road",
    "Industrial": "Industrial Buildings",
    "Pasture": "Pasture Land",
    "PermanentCrop": "Permanent Crop Land",
    "Residential": "Residential Buildings",
    "River": "River",
    "SeaLake": "Sea or Lake",
}

def split_test_into_given_query_db(test_data, given_size=10, query_ratio=0.2):
    """
    test_data -> given, query, db
    - given: 5/cls 
    - query: remain 20%
    - db: remain 80%
    """
    label_to_items = defaultdict(list)
    for item in test_data:
        label_to_items[item.label].append(item)

    given = []
    query = []
    db = []

    for label in sorted(label_to_items.keys()):
        items = label_to_items[label]
        if len(items) < given_size:
            # raise ValueError(f"Class {label} has less than {given_size} test samples, cannot split 'given'.")
            print(f"Class {label} has less than {given_size} test samples, cannot split 'given'.")
            continue
        # Given: 5 
        given.extend(items[:given_size])
        remaining = items[given_size:]

        # Query: 20% of remaining
        n_query = max(1, int(len(remaining) * query_ratio))
        query.extend(remaining[:n_query])
        db.extend(remaining[n_query:])
        
    return given, query, db


@DATASET_REGISTRY.register()
class EuroSAT(DatasetBase):

    dataset_dir = "eurosat"

    def __init__(self, cfg):
        ###
        random.seed(cfg.SEED)
        np.random.seed(cfg.SEED)
        torch.manual_seed(cfg.SEED)

        root = os.path.abspath(os.path.expanduser(cfg.DATASET.ROOT))
        self.dataset_dir = os.path.join(root, self.dataset_dir)
        self.image_dir = os.path.join(self.dataset_dir, "2750")
        self.split_path = os.path.join(self.dataset_dir, "split_zhou_EuroSAT.json")
        self.split_fewshot_dir = os.path.join(self.dataset_dir, "split_fewshot")
        mkdir_if_missing(self.split_fewshot_dir)

        if os.path.exists(self.split_path):
            train, val, test = OxfordPets.read_split(self.split_path, self.image_dir)
        else:
            train, val, test = DTD.read_and_split_data(self.image_dir, new_cnames=NEW_CNAMES)
            OxfordPets.save_split(train, val, test, self.split_path, self.image_dir)

        ### given/query/db
        test_given, test_query, test_db = split_test_into_given_query_db(test)

        num_shots = cfg.DATASET.NUM_SHOTS
        if num_shots >= 1:
            seed = cfg.SEED
            preprocessed = os.path.join(self.split_fewshot_dir, f"shot_{num_shots}-seed_{seed}.pkl")
            
            if os.path.exists(preprocessed):
                print(f"Loading preprocessed few-shot data from {preprocessed}")
                with open(preprocessed, "rb") as file:
                    data = pickle.load(file)
                    train, val = data["train"], data["val"]
            else:
                train = self.generate_fewshot_dataset(train, num_shots=num_shots)
                val = self.generate_fewshot_dataset(val, num_shots=min(num_shots, 4))
                data = {"train": train, "val": val}
                print(f"Saving preprocessed few-shot data to {preprocessed}")
                with open(preprocessed, "wb") as file:
                    pickle.dump(data, file, protocol=pickle.HIGHEST_PROTOCOL)

        subsample = cfg.DATASET.SUBSAMPLE_CLASSES

        train, val, test, test_given, test_query, test_db = OxfordPets.subsample_classes(train, val, test, test_given, test_query, test_db, subsample=subsample)

        super().__init__(train_x=train, val=val, test=test, test_given=test_given, test_query=test_query, test_db=test_db)

    def update_classname(self, dataset_old):
        dataset_new = []
        for item_old in dataset_old:
            cname_old = item_old.classname
            cname_new = NEW_CLASSNAMES[cname_old]
            item_new = Datum(impath=item_old.impath, label=item_old.label, classname=cname_new)
            dataset_new.append(item_new)
        return dataset_new
