"""SDK configuration."""

from typing import Optional

from pydantic_settings import BaseSettings, SettingsConfigDict

from ._constants import (
    DEFAULT_BASE_URL,
    DEFAULT_CDN_URL,
    DEFAULT_CONNECT_TIMEOUT,
    DEFAULT_DJANGO_URL,
    DEFAULT_MAX_RETRIES,
    DEFAULT_OPENAI_URL,
    DEFAULT_OPENROUTER_URL,
    DEFAULT_TIMEOUT,
)


class SDKConfig(BaseSettings):
    """SDK configuration with environment variable support."""

    model_config = SettingsConfigDict(
        env_prefix="SDKROUTER_",
        env_file=".env",
        extra="ignore",
    )

    # API Keys
    api_key: Optional[str] = None
    openrouter_api_key: Optional[str] = None
    openai_api_key: Optional[str] = None

    # Base URLs (for self-hosted or direct)
    base_url: str = DEFAULT_BASE_URL
    django_url: str = DEFAULT_DJANGO_URL
    cdn_url: str = DEFAULT_CDN_URL

    # Direct provider URLs (bypass self-hosted)
    openrouter_url: str = DEFAULT_OPENROUTER_URL
    openai_url: str = DEFAULT_OPENAI_URL

    # Routing mode
    use_self_hosted: bool = True  # False = direct to OpenRouter/OpenAI

    # Timeouts
    timeout: float = DEFAULT_TIMEOUT
    connect_timeout: float = DEFAULT_CONNECT_TIMEOUT

    # Retry
    max_retries: int = DEFAULT_MAX_RETRIES


_config: Optional[SDKConfig] = None


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


def configure(**kwargs) -> SDKConfig:
    """Configure SDK with custom settings."""
    global _config
    _config = SDKConfig(**kwargs)
    return _config


def reset_config() -> None:
    """Reset configuration to defaults."""
    global _config
    _config = None
