import json
import os
import re
import numpy as np
from collections import defaultdict
from datetime import datetime, timedelta, timezone

import huggingface_hub
from huggingface_hub import ModelCard
from huggingface_hub.hf_api import ModelInfo
from transformers import AutoConfig
from transformers.models.auto.tokenization_auto import AutoTokenizer

from src.display.utils import TEXT_TASKS, VISION_TASKS, NUM_EXPECTED_EXAMPLES

def check_model_card(repo_id: str) -> tuple[bool, str]:
    """Checks if the model card and license exist and have been filled"""
    try:
        card = ModelCard.load(repo_id)
    except huggingface_hub.utils.EntryNotFoundError:
        return False, "Please add a model card to your model to explain how you trained/fine-tuned it."

    # Enforce license metadata
    if card.data.license is None:
        if not ("license_name" in card.data and "license_link" in card.data):
            return False, (
                "License not found. Please add a license to your model card using the `license` metadata or a"
                " `license_name`/`license_link` pair."
            )

    # Enforce card content
    if len(card.text) < 200:
        return False, "Please add a description to your model card, it is too short."

    return True, ""

def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=False, test_tokenizer=False) -> tuple[bool, str]:
    """Checks if the model model_name is on the hub, and whether it (and its tokenizer) can be loaded with AutoClasses."""
    try:
        config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
        if test_tokenizer:
            try:
                tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
            except ValueError as e:
                return (
                    False,
                    f"uses a tokenizer which is not in a transformers release: {e}",
                    None
                )
            except Exception as e:
                return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)
        return True, None, config

    except ValueError:
        return (
            False,
            "needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",
            None
        )

    except Exception as e:
        return False, "was not found on hub!", None


def get_model_size(model_info: ModelInfo, precision: str):
    """Gets the model size from the configuration, or the model name if the configuration does not contain the information."""
    try:
        model_size = round(model_info.safetensors["total"] / 1e9, 3)
    except (AttributeError, TypeError):
        return 0  # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py

    size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
    model_size = size_factor * model_size
    return model_size

def get_model_arch(model_info: ModelInfo):
    """Gets the model architecture from the configuration"""
    return model_info.config.get("architectures", "Unknown")

def already_submitted_models(requested_models_dir: str) -> set[str]:
    """Gather a list of already submitted models to avoid duplicates"""
    depth = 1
    file_names = []
    users_to_submission_dates = defaultdict(list)

    for root, _, files in os.walk(requested_models_dir):
        current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
        if current_depth == depth:
            for file in files:
                if not file.endswith(".json"):
                    continue
                with open(os.path.join(root, file), "r") as f:
                    info = json.load(f)
                    file_names.append(f"{info['model']}_{info['revision']}_{info['track']}")

                    # Select organisation
                    if info["model"].count("/") == 0 or "submitted_time" not in info:
                        continue
                    organisation, _ = info["model"].split("/")
                    users_to_submission_dates[organisation].append(info["submitted_time"])

    return set(file_names), users_to_submission_dates

def is_valid_predictions(predictions: dict) -> tuple[bool, str]:
    out_msg = ""
    for task in TEXT_TASKS:
        if task not in predictions:
            out_msg = f"Error: {task} not present"
            break
        for subtask in TEXT_TASKS[task]:
            if subtask not in predictions[task]:
                out_msg = f"Error: {subtask} not present under {task}"
                break
        if out_msg != "":
            break
    if "vqa" in predictions or "winoground" in predictions or "devbench" in predictions:
        for task in VISION_TASKS:
            if task not in predictions:
                out_msg = f"Error: {task} not present"
                break
            for subtask in VISION_TASKS[task]:
                if subtask not in predictions[task]:
                    out_msg = f"Error: {subtask} not present under {task}"
                    break
            if out_msg != "":
                break
    
    # Make sure all examples have predictions, and that predictions are the correct type
    for task in predictions:
        for subtask in predictions[task]:
            if task == "devbench":
                a = np.array(predictions[task][subtask]["predictions"])
                if subtask == "sem-things":
                    required_shape = (1854, 1854)
                elif subtask == "gram-trog":
                    required_shape = (76, 4, 1)
                elif subtask == "lex-viz_vocab":
                    required_shape = (119, 4, 1)
                if a.shape[0] != required_shape[0] or a.shape[1] != required_shape[1]:
                    out_msg = f"Error: Wrong shape for results for `{subtask}` in `{task}`."
                    break
                if not str(a.dtype).startswith("float"):
                    out_msg = f"Error: Results for `{subtask}` ({task}) \
                        should be floats but aren't."
                    break
                continue
        
            num_expected_examples = NUM_EXPECTED_EXAMPLES[task][subtask]
            if len(predictions[task][subtask]["predictions"]) != num_expected_examples:
                out_msg = f"Error: {subtask} has the wrong number of examples."
                break

            if task == "glue":
                if type(predictions[task][subtask]["predictions"][0]["pred"]) != int:
                    out_msg = f"Error: results for `{subtask}` (`{task}`) should be integers but aren't."
                    break
            else:
                if type(predictions[task][subtask]["predictions"][0]["pred"]) != str:
                    out_msg = f"Error: results for `{subtask}` (`{task}`) should be strings but aren't."
                    break

        if out_msg != "":
            break
        
    if out_msg != "":
        return False, out_msg
    return True, "Upload successful."