"""
Configuration management for kvict Proxy.

Follows the same dataclass + os.getenv + singleton pattern as packages/caae/config.py.
"""

import os
from dataclasses import dataclass, field
from typing import Dict, Any, Literal


@dataclass
class ProxyConfig:
    """
    Configuration for kvict Proxy service.

    All values can be overridden via environment variables prefixed with PROXY_.
    """

    # Service
    host: str = field(default_factory=lambda: os.getenv("PROXY_HOST", "0.0.0.0"))
    port: int = field(default_factory=lambda: int(os.getenv("PROXY_PORT", "8080")))
    log_level: str = field(default_factory=lambda: os.getenv("PROXY_LOG_LEVEL", "INFO"))

    # Provider
    provider: str = field(default_factory=lambda: os.getenv("PROXY_PROVIDER", "openai"))
    provider_base_url: str = field(
        default_factory=lambda: os.getenv("PROXY_PROVIDER_BASE_URL", "")
    )

    # Cache
    cache_ttl_seconds: int = field(
        default_factory=lambda: int(os.getenv("PROXY_CACHE_TTL_SECONDS", "3600"))
    )
    cache_max_entries: int = field(
        default_factory=lambda: int(os.getenv("PROXY_CACHE_MAX_ENTRIES", "10000"))
    )

    # CAAE-inspired cache eviction cost model
    # Higher = more aggressive retention of expensive-to-regenerate items
    cost_model_weight_prompt_tokens: float = field(
        default_factory=lambda: float(
            os.getenv("PROXY_COST_WEIGHT_PROMPT_TOKENS", "1.2")
        )
    )
    cost_model_weight_model_cost: float = field(
        default_factory=lambda: float(os.getenv("PROXY_COST_WEIGHT_MODEL_COST", "2.5"))
    )
    cost_model_decay_rate: float = field(
        default_factory=lambda: float(os.getenv("PROXY_COST_DECAY_RATE", "0.001"))
    )

    # Circuit breaker for provider failover
    circuit_breaker_threshold_ms: float = field(
        default_factory=lambda: float(os.getenv("PROXY_CB_THRESHOLD_MS", "5000.0"))
    )
    circuit_breaker_cooldown_ms: float = field(
        default_factory=lambda: float(os.getenv("PROXY_CB_COOLDOWN_MS", "30000.0"))
    )
    circuit_breaker_failure_threshold: int = field(
        default_factory=lambda: int(os.getenv("PROXY_CB_FAILURE_THRESHOLD", "3"))
    )
    circuit_breaker_recovery_threshold: int = field(
        default_factory=lambda: int(os.getenv("PROXY_CB_RECOVERY_THRESHOLD", "2"))
    )

    # Store
    store_backend: str = field(
        default_factory=lambda: os.getenv("PROXY_STORE_BACKEND", "sqlite")
    )
    db_path: str = field(
        default_factory=lambda: os.getenv("PROXY_DB_PATH", "kvict_proxy.db")
    )
    redis_url: str = field(
        default_factory=lambda: os.getenv("PROXY_REDIS_URL", "redis://localhost:6379")
    )

    # Savings display
    avg_tokens_per_message: int = field(
        default_factory=lambda: int(os.getenv("PROXY_AVG_TOKENS_PER_MESSAGE", "750"))
    )

    def to_dict(self) -> Dict[str, Any]:
        """Convert config to dictionary for logging/serialization."""
        return {
            "host": self.host,
            "port": self.port,
            "provider": self.provider,
            "cache_ttl_seconds": self.cache_ttl_seconds,
            "cache_max_entries": self.cache_max_entries,
            "store_backend": self.store_backend,
            "circuit_breaker_threshold_ms": self.circuit_breaker_threshold_ms,
        }


# Global config instance
_config: ProxyConfig | None = None


def get_config() -> ProxyConfig:
    """Get or create global configuration instance."""
    global _config
    if _config is None:
        _config = ProxyConfig()
    return _config


def set_config(config: ProxyConfig) -> None:
    """Set global configuration instance (useful for testing)."""
    global _config
    _config = config
