from __future__ import annotations

import json
import os
import random
from importlib import resources


def load_snark_map() -> dict[str, list[str]]:
    data = resources.files("dont_hallucinate").joinpath("snark.json").read_text(encoding="utf-8")
    payload = json.loads(data)
    return {str(k): list(v) for k, v in payload.items()}


def detect_agent() -> str:
    """Best-effort detection of which AI agent is running."""
    env = os.environ

    if any(k.startswith("CURSOR_") for k in env):
        return "Cursor"

    if env.get("AIDER_MODEL") or env.get("AIDER_CHAT_LANGUAGE"):
        return "Aider"

    if any(k.startswith("WINDSURF_") for k in env):
        return "Windsurf"

    if env.get("GITHUB_COPILOT_TOKEN") or any(k.startswith("COPILOT_") for k in env):
        return "Copilot"

    if env.get("DEVIN_API_KEY") or "devin" in env.get("USER", "").lower():
        return "Devin"

    if env.get("ANTHROPIC_API_KEY") or env.get("CLAUDE_MODEL"):
        return "Claude"

    if env.get("OPENAI_API_KEY"):
        return "GPT"

    return "your agent"


def pick_roast(
    snark_map: dict[str, list[str]],
    error_type: str,
    *,
    agent: str = "your agent",
    cmd_name: str = "",
    flag: str = "that flag",
    missing: str = "that",
    cmd: str = "",
) -> str:
    # Build pool from error type + command-specific extras
    pool = list(snark_map.get(error_type) or snark_map.get("generic_error") or ["No roast available."])
    cmd_key = f"cmd_{cmd_name}" if cmd_name else None
    if cmd_key and cmd_key in snark_map:
        pool = pool + snark_map[cmd_key]

    raw = random.choice(pool)

    # Safe substitution — avoid .format() blowing up on user-provided strings with braces
    result = raw
    result = result.replace("{agent}", agent)
    result = result.replace("{flag}", flag)
    result = result.replace("{cmd}", cmd_name or cmd or "that command")
    result = result.replace("{missing}", missing)
    return result
