"""provider_routes.py — FastAPI router for LLM provider management.

Mounted by gui_backend.py or src/llm/__init__.py.
All logic lives in src/llm/provider_admin.py which IS properly bundled by PyInstaller.

V2 routes are the SINGLE SOURCE OF TRUTH for LLM config APIs.
V1 routes in gui_backend.py are MONKEY-PATCHED at runtime by
src/llm/_patch_v1_routes() to delegate to these implementations.
"""

from __future__ import annotations

from fastapi import APIRouter

router = APIRouter(prefix="/api/v2")


@router.get("/providers")
def get_providers():
    try:
        from src.llm.provider_admin import list_providers
        return list_providers()
    except Exception as e:
        return {"success": False, "error": str(e), "trace": "v2_get_providers"}


@router.post("/providers")
def save_provider(provider: dict):
    from src.llm.provider_admin import save_provider as _sp
    return _sp(
        provider.get("name", ""),
        provider.get("baseUrl", ""),
        provider.get("api", ""),
        provider.get("apiKey", ""),
        provider.get("models", []),
    )


@router.delete("/providers/{name}")
def delete_provider(name: str):
    from src.llm.provider_admin import delete_provider as _dp
    return _dp(name)


@router.get("/agent_models")
def get_agent_models():
    """Return all agent roles with model info + api_key status + ALL provider models."""
    try:
        from src.llm.config import load_agent_models, load_llm_providers, get_api_key
        from src.llm.provider_admin import read_allowed_models

        agents = load_agent_models() or {}
        providers = load_llm_providers()

        result = []
        for role, agent in agents.items():
            model_id = agent.get("model", "")
            provider_name = model_id.split("/")[0] if "/" in model_id else ""
            provider_config = providers.get(provider_name, {})
            has_key = bool(get_api_key(provider_config))
            result.append({
                "role": role,
                "model": model_id,
                "status": "ready" if has_key else "no_api_key",
                "api_key_configured": has_key,
                "provider": provider_name,
            })

        available_models = []
        seen = set()
        for role_cfg in agents.values():
            mid = str(role_cfg.get("model", "") or "").strip()
            if mid and mid not in seen:
                available_models.append(mid)
                seen.add(mid)
        try:
            for mid in read_allowed_models():
                if mid and mid not in seen:
                    available_models.append(mid)
                    seen.add(mid)
        except Exception:
            pass

        return {"success": True, "agents": result, "available_models": available_models}
    except Exception as e:
        return {"success": False, "error": str(e), "trace": "v2_get_agent_models"}


@router.post("/agent_models")
def save_agent_models(agents: list[dict]):
    from src.llm.provider_admin import save_agent_models as _sam
    return _sam(agents)


@router.post("/providers/test")
def test_provider(provider: dict):
    """Real inference test — Phase 1 /models + Phase 2 /chat/completions."""
    import requests

    url = str(provider.get("baseUrl", "")).rstrip("/")
    api_key = str(provider.get("apiKey", "") or "")
    api_type = str(provider.get("api", "openai-completions") or "openai-completions")

    if not api_key:
        return {"success": False, "error": "API Key 为空，请先填写 Key 再测试"}

    if api_type in ("openai-responses", "openai-completions"):
        # Phase 1: connectivity check (try /models first)
        models_ok = False
        try:
            resp = requests.get(
                f"{url}/models",
                headers={"Authorization": f"Bearer {api_key}"},
                timeout=8,
            )
            models_ok = resp.status_code == 200
        except Exception:
            pass

        # Phase 2: real inference test
        try:
            resp = requests.post(
                f"{url}/chat/completions",
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
                json={
                    "model": (provider.get("models") or [{}])[0].get("id", "") if provider.get("models") else "",
                    "messages": [{"role": "user", "content": "Hi"}],
                    "max_tokens": 5,
                },
                timeout=15,
            )
            if resp.status_code == 200:
                data = resp.json()
                reply = data.get("choices", [{}])[0].get("message", {}).get("content", "")
                return {
                    "success": True,
                    "message": f"推理测试通过 ✅ {f'模型回复: {reply[:50]}' if reply else ''}",
                    "models_ok": models_ok,
                }
            err_text = resp.text[:300]
            if resp.status_code == 401:
                return {"success": False, "error": "认证失败 (401)：API Key 无效或已过期", "detail": err_text}
            if resp.status_code == 403:
                return {"success": False, "error": "权限不足 (403)：余额不足或无权访问", "detail": err_text}
            if resp.status_code == 404:
                return {"success": False, "error": f"接口不存在 (404)：baseUrl 可能缺少 /v1 后缀。当前: {url}/chat/completions", "detail": err_text}
            return {"success": False, "error": f"推理失败 (HTTP {resp.status_code})", "detail": err_text, "models_ok": models_ok}
        except Exception as e:
            return {"success": False, "error": f"连接异常: {str(e)[:200]}", "models_ok": models_ok}

    elif api_type == "anthropic-messages":
        # Phase 1: connectivity check
        models_ok = False
        try:
            resp = requests.get(
                f"{url}/models",
                headers={
                    "x-api-key": api_key,
                    "anthropic-version": "2023-06-01",
                },
                timeout=8,
            )
            models_ok = resp.status_code == 200
        except Exception:
            pass

        # Phase 2: real inference test
        try:
            resp = requests.post(
                f"{url}/messages",
                headers={
                    "x-api-key": api_key,
                    "anthropic-version": "2023-06-01",
                    "Content-Type": "application/json",
                },
                json={
                    "model": (provider.get("models") or [{}])[0].get("id", ""),
                    "max_tokens": 5,
                    "messages": [{"role": "user", "content": "Hi"}],
                },
                timeout=15,
            )
            if resp.status_code == 200:
                data = resp.json()
                reply = data.get("content", [{}])[0].get("text", "") if data.get("content") else ""
                return {
                    "success": True,
                    "message": f"推理测试通过 ✅ {f'模型回复: {reply[:50]}' if reply else ''}",
                    "models_ok": models_ok,
                }
            err_text = resp.text[:300]
            if resp.status_code == 401:
                return {"success": False, "error": "认证失败 (401)：API Key 无效或已过期", "detail": err_text}
            if resp.status_code == 403:
                return {"success": False, "error": "权限不足 (403)：余额不足或无权访问", "detail": err_text}
            if resp.status_code == 404:
                return {"success": False, "error": f"接口不存在 (404)：请检查 API 端点是否正确。当前: {url}/messages", "detail": err_text}
            return {"success": False, "error": f"推理失败 (HTTP {resp.status_code})", "detail": err_text, "models_ok": models_ok}
        except Exception as e:
            return {"success": False, "error": f"连接异常: {str(e)[:200]}", "models_ok": models_ok}

    return {"success": False, "error": f"不支持的 API 类型: {api_type}"}


@router.get("/metrics")
def get_llm_metrics_endpoint():
    """Return LLM call metrics — success rate, latency, recent failures."""
    try:
        from src.llm import get_llm_metrics
        return {"success": True, **get_llm_metrics()}
    except Exception as e:
        return {"success": False, "error": str(e)}
