"""
Shadow AI Detector — flags unapproved models and services.

Compares observed gateway traffic against an approved models list.
Any model or provider not on the list triggers a shadow AI alert.
"""

import os
import json
from dataclasses import dataclass
from typing import Optional

try:
    import yaml
    HAS_YAML = True
except ImportError:
    HAS_YAML = False

from air_blackbox.gateway_client import GatewayStatus


@dataclass
class ShadowAlert:
    model: str
    provider: str
    runs_observed: int
    severity: str  # "high", "medium", "low"
    reason: str


def detect_shadow_ai(status: GatewayStatus, approved_path: Optional[str] = None) -> list[ShadowAlert]:
    """Detect unapproved AI models and providers.

    Args:
        status: GatewayStatus with observed traffic
        approved_path: Path to YAML/JSON with approved models list.
                      If None, all models are flagged as "unverified".

    Returns:
        List of ShadowAlert objects
    """
    approved = _load_approved_list(approved_path)
    alerts = []

    for model in status.models_observed:
        runs = sum(1 for r in status.recent_runs if r.get("model") == model)
        provider = _guess_provider_simple(model)

        if approved is None:
            # No approved list = everything is unverified
            alerts.append(ShadowAlert(
                model=model, provider=provider, runs_observed=runs,
                severity="low",
                reason="No approved model registry configured. Run: air-blackbox discover --init-registry",
            ))
        elif model not in approved.get("models", []):
            alerts.append(ShadowAlert(
                model=model, provider=provider, runs_observed=runs,
                severity="high" if runs > 10 else "medium",
                reason=f"Model '{model}' not in approved registry. {runs} requests observed.",
            ))

    # Check providers
    if approved:
        for provider in status.providers_observed:
            if provider not in approved.get("providers", []):
                alerts.append(ShadowAlert(
                    model="*", provider=provider,
                    runs_observed=sum(1 for r in status.recent_runs if r.get("provider") == provider),
                    severity="high",
                    reason=f"Provider '{provider}' not in approved registry.",
                ))

    return alerts


def generate_approved_registry(status: GatewayStatus) -> dict:
    """Generate a starter approved-models.yaml from current traffic.

    Use this to bootstrap the registry from what's currently running.
    """
    return {
        "version": "1.0",
        "description": "Approved AI models and providers — generated by air-blackbox discover",
        "generated_at": __import__("datetime").datetime.utcnow().isoformat() + "Z",
        "models": sorted(status.models_observed),
        "providers": sorted(status.providers_observed),
    }


def _load_approved_list(path: Optional[str]) -> Optional[dict]:
    if path is None:
        # Try default locations
        for candidate in ["approved-models.yaml", "approved-models.yml", "approved-models.json"]:
            if os.path.exists(candidate):
                path = candidate
                break
    if path is None:
        return None
    try:
        with open(path, "r") as f:
            if path.endswith(".json"):
                return json.load(f)
            elif HAS_YAML:
                return yaml.safe_load(f)
            else:
                return json.load(f)  # Try JSON as fallback
    except Exception:
        return None


def _guess_provider_simple(model: str) -> str:
    m = model.lower()
    if any(x in m for x in ["gpt", "o1", "o3"]): return "openai"
    if any(x in m for x in ["claude", "sonnet", "haiku"]): return "anthropic"
    if any(x in m for x in ["gemini", "gemma"]): return "google"
    if any(x in m for x in ["llama"]): return "meta"
    if any(x in m for x in ["mistral", "mixtral"]): return "mistral"
    return "unknown"
