"""Global configuration management."""

from __future__ import annotations

import os
from typing import Any

from pydantic import BaseModel, field_validator


class Config(BaseModel):
    """Global configuration singleton for provider settings, cache, defaults.

    Attributes:
        provider: Provider name ("anthropic", "openai", "local").
        model: Model name (e.g., "claude-sonnet-4-20250514").
        api_key: Explicit API key (overrides env var).
        base_url: Custom endpoint (for local/proxy).
        default_threshold: Default threshold for all checks.
        max_retries: LLM API retry count.
        timeout_seconds: LLM API timeout.
        cache_enabled: Enable result caching.
        cache_dir: Cache directory path.
        parallelism: Max concurrent check executions.
        verbose: Enable detailed logging.
    """

    provider: str | None = None
    model: str | None = None
    api_key: str | None = None
    base_url: str | None = None
    default_threshold: float = 0.5
    max_retries: int = 3
    timeout_seconds: float = 30.0
    cache_enabled: bool = True
    cache_dir: str = ".ai_qa_cache"
    parallelism: int = 4
    verbose: bool = False

    @field_validator("default_threshold")
    @classmethod
    def validate_default_threshold(cls, v: float) -> float:
        """Validate default_threshold is between 0.0 and 1.0."""
        if not (0.0 <= v <= 1.0):
            raise ValueError(
                f"default_threshold must be between 0.0 and 1.0, got {v}"
            )
        return v

    @field_validator("max_retries")
    @classmethod
    def validate_max_retries(cls, v: int) -> int:
        """Validate max_retries is positive."""
        if v < 0:
            raise ValueError(f"max_retries must be >= 0, got {v}")
        return v

    @field_validator("timeout_seconds")
    @classmethod
    def validate_timeout(cls, v: float) -> float:
        """Validate timeout_seconds is positive."""
        if v <= 0:
            raise ValueError(f"timeout_seconds must be > 0, got {v}")
        return v

    @field_validator("parallelism")
    @classmethod
    def validate_parallelism(cls, v: int) -> int:
        """Validate parallelism is positive."""
        if v <= 0:
            raise ValueError(f"parallelism must be > 0, got {v}")
        return v


# Global singleton instance
_global_config: Config | None = None


def _auto_detect_provider() -> str | None:
    """Auto-detect provider from environment variables.

    Returns:
        "anthropic" if ANTHROPIC_API_KEY is set.
        "openai" if OPENAI_API_KEY is set.
        None if neither is set.
    """
    if os.getenv("ANTHROPIC_API_KEY"):
        return "anthropic"
    if os.getenv("OPENAI_API_KEY"):
        return "openai"
    return None


def configure(**kwargs: Any) -> Config:
    """Set global config and return it.

    Args:
        **kwargs: Config fields to set.

    Returns:
        The updated Config instance.

    Raises:
        ValueError: If any field is invalid.
    """
    global _global_config
    _global_config = Config(**kwargs)
    return _global_config


def get_config() -> Config:
    """Return current config.

    If never configured, returns defaults with auto-detected provider.

    Returns:
        The current Config instance.
    """
    global _global_config
    if _global_config is None:
        _global_config = Config(provider=_auto_detect_provider())
    return _global_config


def reset_config() -> None:
    """Reset config to None (for testing)."""
    global _global_config
    _global_config = None
