"""Centralized application configuration.

All settings are loaded from environment variables (or a .env file)
once at startup. Provider-specific defaults (model names, base URLs)
are resolved by the provider adapters, not here.
"""

import logging.config
from contextvars import ContextVar
from enum import StrEnum
from pathlib import Path
from typing import Literal

from pydantic_settings import BaseSettings
from pydantic_settings import SettingsConfigDict

logger = logging.getLogger(__name__)


class Provider(StrEnum):
    OPENROUTER = "openrouter"


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore",
    )

    # --- AI provider ---
    provider: Provider = Provider.OPENROUTER
    openrouter_api_key: str
    provider_model: str | None = None
    openrouter_http_referer: str | None = None
    openrouter_app_title: str | None = None

    # --- runtime environment ---
    environment: Literal["development", "test", "production"] = "development"

    # --- persistence ---
    database_url: str = "sqlite:///./transcription.db"
    bootstrap_schema_on_startup: bool | None = None
    sqlite_check_same_thread: bool = False

    # --- filesystem paths ---
    upload_dir: Path = Path("./uploads")
    prompt_dir: Path = Path("./prompts")

    # --- worker reliability ---
    worker_max_retries: int = 0
    worker_retry_backoff_seconds: float = 0.0

    @property
    def should_bootstrap_schema(self) -> bool:
        """Return whether startup should auto-create schema for this environment."""
        if self.bootstrap_schema_on_startup is not None:
            return self.bootstrap_schema_on_startup
        return self.environment in {"development", "test"}


_settings: ContextVar[Settings | None] = ContextVar("settings", default=None)


def get_settings(**kwargs) -> Settings:
    settings = _settings.get()
    if settings is None:
        settings = Settings(**kwargs)  # pyright: ignore[reportCallIssue]
        _settings.set(settings)
    return settings


LOGGING_CONFIG: dict[str, object] = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "standard": {
            "format": "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
            "datefmt": "%Y-%m-%d %H:%M:%S",
        }
    },
    "handlers": {
        "console": {
            "class": "logging.StreamHandler",
            "formatter": "standard",
            "stream": "ext://sys.stdout",
        }
    },
    "root": {
        "level": "INFO",
        "handlers": ["console"],
    },
    "loggers": {
        "transcription": {
            "level": "DEBUG",
            "handlers": ["console"],
            "propagate": False,
        }
    },
}


def configure_logging() -> None:
    """Configure root logging once at startup."""
    logging.config.dictConfig(LOGGING_CONFIG)
    logger.debug("Logging configured")
