import json
import logging
import os

from colorama import Fore, Style

logger = logging.getLogger(__name__)

BENCHMARKS_FILE = os.path.join(
    os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "benchmarks", "data", "llm_benchmarks.json"
)


def check_model_benchmarks(configs):
    """
    Checks the configured AI models against the local benchmark database.
    Emits warnings if the user is running untested or underperforming models
    that could lead to agent hallucinations or broken interactions.
    """
    if not os.path.exists(BENCHMARKS_FILE):
        return

    try:
        with open(BENCHMARKS_FILE, "r") as f:
            data = json.load(f)
            benchmarks = data.get("models", {})
    except Exception as e:
        logger.warning(f"Could not load LLM benchmarks: {e}")
        return

    def _eval_model(model_name: str, context: str):
        if not model_name:
            return

        if model_name not in benchmarks:
            logger.warning(
                f"⚠️ [Benchmark Guard] Model '{model_name}' (for {context}) is COMPLETELY UNTESTED "
                f"for the Agent. Expect severe hallucinations or crashed agents.",
                extra={"color": f"{Style.BRIGHT}{Fore.RED}"},
            )
            return

        scores = benchmarks[model_name]

        # Telepathic/Vision tasks require high structural strictness
        if context == "Vision/Telepathic":
            score = scores.get("telepathic_score", 0)
        else:
            score = scores.get("resonance_score", 0)

        if score < 50:
            logger.error(
                f"⛔ [Benchmark Guard] Model '{model_name}' (for {context}) achieved a CRITICAL FAILURE score "
                f"of {score}/100. Autonomous safety is compromised. DO NOT RUN UNATTENDED.",
                extra={"color": f"{Style.BRIGHT}{Fore.RED}"},
            )
        elif score < 80:
            logger.warning(
                f"⚠️ [Benchmark Guard] Model '{model_name}' (for {context}) achieved a SUB-STANDARD score "
                f"of {score}/100. It may occasionally hallucinate UI elements or misinterpret semantics.",
                extra={"color": f"{Style.BRIGHT}{Fore.YELLOW}"},
            )
        else:
            logger.info(
                f"✅ [Benchmark Guard] Model '{model_name}' (for {context}) passes safety benchmarks ({score}/100).",
                extra={"color": f"{Style.BRIGHT}{Fore.GREEN}"},
            )

    # Which models did the user configure?
    telepathic_model = getattr(configs.args, "ai_telepathic_model", None)
    text_model = getattr(configs.args, "ai_model", None)
    condenser_model = getattr(configs.args, "ai_condenser_model", None)

    _eval_model(telepathic_model, "Vision/Telepathic")

    if text_model and text_model != telepathic_model:
        _eval_model(text_model, "Dopamine/Resonance")

    if condenser_model and condenser_model != text_model and condenser_model != telepathic_model:
        _eval_model(condenser_model, "Context Condensation")
