"""Diagnostic checks: LLM provider configuration and model aliases."""
from __future__ import annotations

from typing import Any

from proxym.config import get_settings


async def check_providers_config() -> dict[str, Any]:
    """Check which LLM providers are configured with API keys."""
    settings = get_settings()
    providers = settings.available_providers()

    provider_details = []
    for name, key in providers.items():
        provider_details.append({
            "name": name,
            "has_key": bool(key) and key != "ollama",
            "is_local": name == "ollama",
            "key_prefix": key[:8] + "..." if key and key != "ollama" and len(key) > 8 else None,
        })

    # Check model aliases resolve to available providers.
    # OpenRouter acts as a universal gateway — if configured, it can serve
    # models from anthropic, google, openai, deepseek, mistral, etc.
    from proxym.providers import MODELS, get_model
    has_openrouter = "openrouter" in providers
    alias_status = []
    for alias, model_name in settings.model_aliases.items():
        spec = get_model(model_name)
        if spec is None:
            for mid, m in MODELS.items():
                if model_name.lower() in mid.lower() or model_name.lower() in m.display_name.lower():
                    spec = m
                    break
        if spec:
            provider = spec.provider
        else:
            provider = model_name.split("/")[0] if "/" in model_name else "anthropic"
            if provider == "gemini":
                provider = "google"
        # Model is available if its direct provider is configured OR if openrouter
        # is configured (openrouter can proxy anthropic, google, openai, etc.)
        available = provider in providers or (has_openrouter and provider != "ollama")
        alias_status.append({
            "alias": alias,
            "model": model_name,
            "provider": provider,
            "available": available,
            "via_openrouter": available and provider not in providers and has_openrouter,
        })

    return {
        "service": "providers",
        "total_providers": len(providers),
        "providers": provider_details,
        "aliases": alias_status,
        "all_aliases_available": all(a["available"] for a in alias_status),
        "details": {},
    }
