"""Application configuration using pydantic-settings."""
from functools import lru_cache
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """Application settings loaded from environment variables."""
    
    # Database
    database_url: str = "sqlite+aiosqlite:///./domainwatch.db"
    
    # JWT Settings
    secret_key: str = "dev-secret-key-change-in-production"
    algorithm: str = "HS256"
    access_token_expire_minutes: int = 1440  # 24 hours
    
    # App Settings
    app_name: str = "DomainWatch"
    debug: bool = True
    site_url: str = "https://pounce.ch"  # Base URL for links in emails/API responses

    # Internal admin operations (server-to-server / cron)
    # MUST be set in production; used for protected internal endpoints.
    internal_api_key: str = ""
    
    # Email Settings (optional)
    smtp_host: str = ""
    smtp_port: int = 587
    smtp_user: str = ""
    smtp_password: str = ""
    email_from: str = ""
    
    # CORS Settings
    cors_origins: str = "http://localhost:3000,http://127.0.0.1:3000"
    
    # Scheduler Settings
    check_hour: int = 6
    check_minute: int = 0
    scheduler_check_interval_hours: int = 24
    enable_scheduler: bool = False  # Run APScheduler jobs in this process (recommend: separate scheduler process)

    # Job Queue / Redis (Phase 2)
    redis_url: str = ""  # e.g. redis://redis:6379/0
    enable_job_queue: bool = False

    # Observability (Phase 2)
    enable_metrics: bool = True
    metrics_path: str = "/metrics"
    enable_db_query_metrics: bool = False
    enable_business_metrics: bool = True
    business_metrics_days: int = 30
    business_metrics_cache_seconds: int = 60

    # Ops / Backups (4B)
    enable_db_backups: bool = False
    backup_dir: str = "backups"
    backup_retention_days: int = 14

    # Ops / Alerting (4B) - no Docker required
    ops_alerts_enabled: bool = False
    ops_alert_recipients: str = ""  # comma-separated emails; if empty -> CONTACT_EMAIL env fallback
    ops_alert_cooldown_minutes: int = 180
    ops_alert_backup_stale_seconds: int = 93600  # ~26h

    # Rate limiting storage (SlowAPI / limits). Use Redis in production.
    rate_limit_storage_uri: str = "memory://"

    # =================================
    # Referral rewards / Anti-fraud (3C.2)
    # =================================
    referral_rewards_enabled: bool = True
    referral_rewards_cooldown_days: int = 7
    referral_rewards_ip_window_days: int = 30
    referral_rewards_require_ip_hash: bool = True

    # =================================
    # Yield / Intent Routing
    # =================================
    # Comma-separated list of nameservers the user must delegate to for Yield.
    # Example: "ns1.pounce.ch,ns2.pounce.ch"
    yield_nameservers: str = "ns1.pounce.ch,ns2.pounce.ch"
    # CNAME/ALIAS target for simpler DNS setup (provider-dependent).
    # Example: "yield.pounce.ch"
    yield_cname_target: str = "yield.pounce.ch"

    @property
    def yield_nameserver_list(self) -> list[str]:
        return [
            ns.strip().lower()
            for ns in (self.yield_nameservers or "").split(",")
            if ns.strip()
        ]

    # Database pooling (PostgreSQL)
    db_pool_size: int = 5
    db_max_overflow: int = 10
    db_pool_timeout: int = 30
    
    # =================================
    # External API Credentials
    # =================================
    
    # DropCatch API (Official Partner API)
    # Docs: https://www.dropcatch.com/hiw/dropcatch-api
    dropcatch_client_id: str = ""
    dropcatch_client_secret: str = ""
    dropcatch_api_base: str = "https://api.dropcatch.com"
    
    # Sedo API (Partner API - XML-RPC)
    # Docs: https://api.sedo.com/apidocs/v1/
    # Find your credentials: Sedo.com → Mein Sedo → API-Zugang
    sedo_partner_id: str = ""
    sedo_sign_key: str = ""
    sedo_api_base: str = "https://api.sedo.com/api/v1/"
    
    # Moz API (SEO Data)
    moz_access_id: str = ""
    moz_secret_key: str = ""

    # =================================
    # LLM Gateway (Ollama / Mistral Nemo)
    # =================================
    llm_gateway_url: str = "http://127.0.0.1:8812"  # reverse-tunnel default on Pounce server
    llm_gateway_api_key: str = ""
    llm_default_model: str = "mistral-nemo:latest"
    
    # ICANN CZDS (Centralized Zone Data Service)
    # For downloading gTLD zone files (.com, .net, .org, etc.)
    # Register at: https://czds.icann.org/
    czds_username: str = ""
    czds_password: str = ""
    czds_data_dir: str = "/data/czds"  # Persistent storage
    
    # Switch.ch Zone Files (.ch, .li)
    switch_data_dir: str = "/data/switch"  # Persistent storage
    
    # Zone File Retention (days to keep historical snapshots)
    zone_retention_days: int = 3
    
    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        extra = "ignore"  # Ignore extra fields in .env


@lru_cache()
def get_settings() -> Settings:
    """Get cached settings instance."""
    return Settings()

