"""Environment API key lookup for LLM providers."""

from __future__ import annotations

import os
from pathlib import Path


_cached_vertex_adc_exists: bool | None = None

_ENV_MAP: dict[str, str] = {
    "openai": "OPENAI_API_KEY",
    "azure-openai-responses": "AZURE_OPENAI_API_KEY",
    "google": "GEMINI_API_KEY",
    "groq": "GROQ_API_KEY",
    "cerebras": "CEREBRAS_API_KEY",
    "xai": "XAI_API_KEY",
    "openrouter": "OPENROUTER_API_KEY",
    "vercel-ai-gateway": "AI_GATEWAY_API_KEY",
    "zai": "ZAI_API_KEY",
    "mistral": "MISTRAL_API_KEY",
    "minimax": "MINIMAX_API_KEY",
    "minimax-cn": "MINIMAX_CN_API_KEY",
    "huggingface": "HF_TOKEN",
    "opencode": "OPENCODE_API_KEY",
    "opencode-go": "OPENCODE_API_KEY",
    "kimi-coding": "KIMI_API_KEY",
}


def _has_vertex_adc_credentials() -> bool:
    """Check if Google Vertex AI Application Default Credentials exist."""
    global _cached_vertex_adc_exists
    if _cached_vertex_adc_exists is not None:
        return _cached_vertex_adc_exists

    gac_path = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS")
    if gac_path:
        _cached_vertex_adc_exists = os.path.exists(gac_path)
    else:
        default_path = Path.home() / ".config" / "gcloud" / "application_default_credentials.json"
        _cached_vertex_adc_exists = default_path.exists()

    return _cached_vertex_adc_exists


def get_env_api_key(provider: str) -> str | None:
    """Get API key for provider from known environment variables.

    Maps provider names to their corresponding environment variable names.
    Returns None if the key is not set.
    """
    # GitHub Copilot: check multiple env vars in order
    if provider == "github-copilot":
        return os.environ.get("COPILOT_GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")

    # Anthropic: ANTHROPIC_OAUTH_TOKEN takes precedence
    if provider == "anthropic":
        return os.environ.get("ANTHROPIC_OAUTH_TOKEN") or os.environ.get("ANTHROPIC_API_KEY")

    # Google Vertex: API key or ADC
    if provider == "google-vertex":
        api_key = os.environ.get("GOOGLE_CLOUD_API_KEY")
        if api_key:
            return api_key

        has_credentials = _has_vertex_adc_credentials()
        has_project = bool(os.environ.get("GOOGLE_CLOUD_PROJECT") or os.environ.get("GCLOUD_PROJECT"))
        has_location = bool(os.environ.get("GOOGLE_CLOUD_LOCATION"))

        if has_credentials and has_project and has_location:
            return "<authenticated>"
        return None

    # Amazon Bedrock: multiple credential sources
    if provider == "amazon-bedrock":
        if (
            os.environ.get("AWS_PROFILE")
            or (os.environ.get("AWS_ACCESS_KEY_ID") and os.environ.get("AWS_SECRET_ACCESS_KEY"))
            or os.environ.get("AWS_BEARER_TOKEN_BEDROCK")
            or os.environ.get("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
            or os.environ.get("AWS_CONTAINER_CREDENTIALS_FULL_URI")
            or os.environ.get("AWS_WEB_IDENTITY_TOKEN_FILE")
        ):
            return "<authenticated>"
        return None

    # Standard env var lookup
    env_var = _ENV_MAP.get(provider)
    return os.environ.get(env_var) if env_var else None
