"""Diagnostic checks: LLM proxy connectivity and models."""
from __future__ import annotations

from typing import Any

import httpx

from proxym.api._diag_common import INTERNAL_PORT
from proxym.config import get_settings


async def check_llm_proxy(base_url: str) -> dict[str, Any]:
    """Check LLM proxy connectivity and available models."""
    settings = get_settings()
    api_key = settings.master_key

    # Try multiple URLs: the passed base_url, then internal loopback
    candidates = [
        base_url.rstrip("/"),
        f"http://127.0.0.1:{INTERNAL_PORT}",
        f"http://localhost:{INTERNAL_PORT}",
    ]
    # Deduplicate while preserving order
    seen = set()
    urls = []
    for u in candidates:
        if u not in seen:
            seen.add(u)
            urls.append(u)

    result = {
        "service": "llm_proxy",
        "url": urls[0],
        "internal_url": urls[0],
        "reachable": False,
        "models_available": 0,
        "details": {},
    }

    for proxy_url in urls:
        try:
            async with httpx.AsyncClient(timeout=5.0) as client:
                health_resp = await client.get(f"{proxy_url}/health")
                if health_resp.status_code == 200:
                    result["reachable"] = True
                    result["url"] = proxy_url
                    result["internal_url"] = proxy_url
                    result["details"]["health"] = health_resp.json()
                    result["details"].pop("error", None)

                    headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
                    models_resp = await client.get(f"{proxy_url}/v1/models", headers=headers)
                    if models_resp.status_code == 200:
                        models_data = models_resp.json()
                        result["models_available"] = len(models_data.get("data", []))
                        result["details"]["aliases"] = [
                            m for m in models_data.get("data", []) if m.get("is_alias")
                        ]
                    break
        except Exception as e:
            result["details"]["error"] = str(e)

    return result
