"""Application settings for DSCons."""

from __future__ import annotations

from functools import lru_cache

try:
    from pydantic_settings import BaseSettings, SettingsConfigDict
except ImportError:  # pragma: no cover
    from pydantic import BaseSettings  # type: ignore

    SettingsConfigDict = dict  # type: ignore


class Settings(BaseSettings):
    """Runtime configuration loaded from environment variables."""

    app_env: str = "development"
    app_name: str = "DSCons API"
    app_version: str = "0.1.0"
    # Default Fallback LLM config
    llm_provider: str = "openai_compatible"
    llm_model_name: str = "stealth/ox-alpha"
    llm_api_base_url: str = "https://openrouter.ai/api/v1"
    llm_api_key: str = "lm-studio"
    request_timeout_seconds: float = 120.0
    llm_max_tokens: int = 16384

    # Multi-Provider Configuration Pool
    # 1. LM Studio Local Engine
    lmstudio_enabled: bool = True
    lmstudio_base_url: str = "http://127.0.0.1:1234/v1"
    lmstudio_model_name: str = "lfm2.5-2.6b"
    lmstudio_api_key: str = "lm-studio"

    # 2. OpenRouter Cloud Engine
    openrouter_enabled: bool = True
    openrouter_base_url: str = "https://openrouter.ai/api/v1"
    openrouter_api_key: str = ""
    openrouter_model_name: str = "liquid/lfm-2.5-2.6b:free"

    # 3. Direct Google Gemini Cloud Engine
    gemini_enabled: bool = True
    gemini_base_url: str = "https://generativelanguage.googleapis.com/v1beta/openai"
    gemini_api_key: str = ""
    gemini_model_name: str = "gemini-3.1-pro"

    # Per-Agent / Persona Provider Routing (mapping agent_code -> provider_name)
    agent_provider_routing: dict[str, str] = {
        "thuy": "openrouter",  # Trợ lý giám đốc & Điều hành
        "minh": "openrouter",  # Điều phối tổng & Pháp lý Luật 2026
        "tung": "openrouter",  # Kiểm toán nội bộ & Soát lỗi
        "quynh": "gemini",  # Kỹ sư QS & Bóc tách BoQ (Gemini 3.1 Pro High Reasoning)
        "hung": "openrouter",  # Kỹ thuật hiện trường & Ca máy
        "thao": "openrouter",  # Hồ sơ pháp lý & Hợp đồng
        "nam": "openrouter",  # Kế toán chi phí & Dòng tiền
        "lan": "openrouter",  # Chăm sóc khách hàng & CĐT
        "phuc": "openrouter",  # Tiến độ & Nhắc việc công trường
    }

    # Custom model name routing override per agent (e.g. {"agent_code": "model_id"})
    agent_model_routing: dict[str, str] = {
        "thuy": "liquid/lfm-2.5-2.6b:free",
        "minh": "liquid/lfm-2.5-2.6b:free",
        "tung": "liquid/lfm-2.5-2.6b:free",
        "quynh": "gemini-3.1-pro",
        "hung": "liquid/lfm-2.5-2.6b:free",
        "thao": "liquid/lfm-2.5-2.6b:free",
        "nam": "liquid/lfm-2.5-2.6b:free",
        "lan": "liquid/lfm-2.5-2.6b:free",
        "phuc": "liquid/lfm-2.5-2.6b:free",
    }

    qdrant_url: str = "http://127.0.0.1:6333"
    qdrant_collection: str = "dscons_knowledge"
    embedding_model_name: str = "vinai/phobert-base-v2"
    embedding_cache_dir: str = ".cache/huggingface"
    embedding_local_files_only: bool = False
    embedding_eager_load: bool = True
    dscons_host: str = "127.0.0.1"
    dscons_port: int = 8000
    # Google OAuth 2.0 & JWT Authentication Config
    google_client_id: str = ""
    google_client_secret: str = ""
    jwt_secret_key: str = "dscons-enterprise-super-secret-key-2026"
    jwt_algorithm: str = "HS256"
    jwt_access_token_expire_minutes: int = 1440  # 24 hours
    app_public_url: str = "https://dinhsonconstruction.com"

    # Cloudflare Enterprise Tunnel Manager
    cloudflared_enabled: bool = True
    cloudflared_tunnel_name: str = "dscons-erp"

    database_url: str = ""
    database_connect_timeout_seconds: int = 3

    # Telegram Enterprise Bot & Notification Suite
    telegram_enabled: bool = True
    telegram_bot_token: str = ""
    telegram_chat_id: str = ""
    telegram_webhook_secret: str = "dscons-telegram-webhook-secret-2026"

    model_config = SettingsConfigDict(
        env_file=".env",
        env_prefix="",
        case_sensitive=False,
        extra="ignore",
    )


@lru_cache(maxsize=1)
def get_settings() -> Settings:
    """Return a cached settings instance."""

    return Settings()
