"""Configuration loaded from environment / .env file."""

from __future__ import annotations

from pydantic import Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """All settings with sensible defaults. Override via env vars or .env file."""

    model_config = {"env_file": ".env", "env_file_encoding": "utf-8", "extra": "ignore"}

    # --- Server ---
    host: str = Field("0.0.0.0", alias="AI_PROXY_HOST")
    port: int = Field(4000, alias="AI_PROXY_PORT")
    master_key: str = Field("sk-proxy-local-dev", alias="AI_PROXY_MASTER_KEY")
    log_level: str = Field("info", alias="AI_PROXY_LOG_LEVEL")

    # --- Redis ---
    redis_url: str = Field("redis://localhost:6379/0", alias="REDIS_URL")

    # --- Provider keys ---
    anthropic_api_key: str = Field("", alias="ANTHROPIC_API_KEY")
    openai_api_key: str = Field("", alias="OPENAI_API_KEY")
    openrouter_api_key: str = Field("", alias="OPENROUTER_API_KEY")
    google_ai_key: str = Field("", alias="GOOGLE_AI_KEY")
    deepseek_api_key: str = Field("", alias="DEEPSEEK_API_KEY")
    groq_api_key: str = Field("", alias="GROQ_API_KEY")
    together_api_key: str = Field("", alias="TOGETHER_API_KEY")
    mistral_api_key: str = Field("", alias="MISTRAL_API_KEY")
    fireworks_api_key: str = Field("", alias="FIREWORKS_API_KEY")
    cerebras_api_key: str = Field("", alias="CEREBRAS_API_KEY")

    # --- Local Ollama ---
    ollama_base_url: str = Field("http://localhost:11434", alias="OLLAMA_BASE_URL")
    ollama_secondary_url: str = Field("", alias="OLLAMA_SECONDARY_URL")

    # --- Delta context buffer ---
    watch_dir: str = Field("./project", alias="WATCH_DIR")
    max_context_tokens: int = Field(120_000, alias="MAX_CONTEXT_TOKENS")
    delta_threshold: float = Field(0.15, alias="DELTA_THRESHOLD")

    # --- Budget ---
    monthly_budget_usd: float = Field(60.0, alias="MONTHLY_BUDGET_USD")
    daily_budget_usd: float = Field(5.0, alias="DAILY_BUDGET_USD")
    max_request_cost_usd: float = Field(2.0, alias="MAX_REQUEST_COST_USD")

    def available_providers(self) -> dict[str, str]:
        """Return mapping of provider name → api key for configured providers."""
        providers = {}
        key_map = {
            "anthropic": self.anthropic_api_key,
            "openai": self.openai_api_key,
            "openrouter": self.openrouter_api_key,
            "google": self.google_ai_key,
            "deepseek": self.deepseek_api_key,
            "groq": self.groq_api_key,
            "together": self.together_api_key,
            "mistral": self.mistral_api_key,
            "fireworks": self.fireworks_api_key,
            "cerebras": self.cerebras_api_key,
        }
        for name, key in key_map.items():
            if key:
                providers[name] = key
        # Ollama is always available (local)
        providers["ollama"] = "ollama"
        return providers


_settings: Settings | None = None


def get_settings() -> Settings:
    global _settings
    if _settings is None:
        _settings = Settings()
    return _settings
