"""Configuration management for LLM Ledger SDK."""

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

from dotenv import load_dotenv

load_dotenv()


@dataclass
class LLMConfig:
    """Configuration for LLM client."""
    
    # API Keys (from environment)
    anthropic_api_key: Optional[str] = field(
        default_factory=lambda: os.getenv("ANTHROPIC_API_KEY")
    )
    openai_api_key: Optional[str] = field(
        default_factory=lambda: os.getenv("OPENAI_API_KEY")
    )
    
    # Database
    database_url: str = field(
        default_factory=lambda: os.getenv("LLM_DATABASE_URL", "sqlite:///llm_gateway.db")
    )
    
    # Cache
    cache_backend: str = field(
        default_factory=lambda: os.getenv("LLM_CACHE_BACKEND", "memory")  # "memory" or "redis"
    )
    redis_url: str = field(
        default_factory=lambda: os.getenv("REDIS_URL", "redis://localhost:6379/0")
    )
    cache_ttl: Optional[int] = field(
        default_factory=lambda: int(os.getenv("LLM_CACHE_TTL", "0")) or None
    )
    
    # Features
    enable_cache: bool = field(
        default_factory=lambda: os.getenv("LLM_ENABLE_CACHE", "true").lower() == "true"
    )
    enable_persistence: bool = field(
        default_factory=lambda: os.getenv("LLM_ENABLE_PERSISTENCE", "true").lower() == "true"
    )
    
    # Defaults
    default_model: str = field(
        default_factory=lambda: os.getenv("LLM_DEFAULT_MODEL", "claude-sonnet-4")
    )
    default_temperature: float = field(
        default_factory=lambda: float(os.getenv("LLM_DEFAULT_TEMPERATURE", "0.0"))
    )
    default_max_tokens: int = field(
        default_factory=lambda: int(os.getenv("LLM_DEFAULT_MAX_TOKENS", "4000"))
    )
    
    # Retry & Timeout
    default_num_retries: int = field(
        default_factory=lambda: int(os.getenv("LLM_DEFAULT_RETRIES", "3"))
    )
    default_timeout: int = field(
        default_factory=lambda: int(os.getenv("LLM_DEFAULT_TIMEOUT", "300"))
    )
    
    # LiteLLM settings
    litellm_kwargs: Dict[str, Any] = field(default_factory=dict)
    
    def __post_init__(self):
        """Validate configuration."""
        if self.cache_backend not in ["memory", "redis"]:
            raise ValueError(f"Invalid cache_backend: {self.cache_backend}")
    
    def to_client_kwargs(self) -> Dict[str, Any]:
        """Convert config to client initialization kwargs."""
        from .cache import InMemoryCache, RedisCache
        
        kwargs = {
            "enable_cache": self.enable_cache,
            "enable_persistence": self.enable_persistence,
            "default_model": self.default_model,
            "database_url": self.database_url,
            "cache_ttl": self.cache_ttl,
            "litellm_kwargs": self.litellm_kwargs
        }
        
        # Set up cache backend
        if self.enable_cache:
            if self.cache_backend == "redis":
                kwargs["cache_backend"] = RedisCache(self.redis_url)
            else:
                kwargs["cache_backend"] = InMemoryCache()
        
        return kwargs


def create_client_from_env() -> 'LedgerClient':
    """
    Create client from environment variables.
    
    Environment variables:
        ANTHROPIC_API_KEY: Anthropic API key
        OPENAI_API_KEY: OpenAI API key
        LLM_DATABASE_URL: Database connection string
        LLM_CACHE_BACKEND: "memory" or "redis"
        REDIS_URL: Redis connection string
        LLM_CACHE_TTL: Cache TTL in seconds (0 = no expiration)
        LLM_ENABLE_CACHE: "true" or "false"
        LLM_ENABLE_PERSISTENCE: "true" or "false"
        LLM_DEFAULT_MODEL: Default model name
        LLM_DEFAULT_TEMPERATURE: Default temperature
        LLM_DEFAULT_MAX_TOKENS: Default max tokens
        LLM_DEFAULT_RETRIES: Default number of retries
        LLM_DEFAULT_TIMEOUT: Default timeout in seconds
    """
    from .client import LedgerClient
    
    config = LLMConfig()
    return LedgerClient(**config.to_client_kwargs())
