from functools import lru_cache from pathlib import Path from pydantic import Field, field_validator from pydantic_settings import BaseSettings, SettingsConfigDict PROJECT_ROOT = Path(__file__).resolve().parents[1] class Settings(BaseSettings): """Application configuration loaded from environment variables.""" model_config = SettingsConfigDict( env_file=PROJECT_ROOT / ".env", env_file_encoding="utf-8", case_sensitive=False, extra="ignore", ) app_name: str = "F1 Live Winner Backend" app_env: str = "development" app_host: str = "0.0.0.0" app_port: int = Field(default=8000, ge=1, le=65535) app_log_level: str = "INFO" model_backend: str = "local" remote_model_url: str | None = None remote_model_api_token: str | None = None remote_model_timeout_seconds: float = 30.0 model_path: Path = Path("models/f1_live_winner_model.pkl") model_schema_path: Path = Path( "models/f1_live_winner_feature_schema.json" ) openf1_enabled: bool = False openf1_base_url: str = "https://api.openf1.org/v1" openf1_api_token: str | None = None openf1_session_key: str = "latest" openf1_poll_interval_seconds: float = Field(default=3.0, ge=1.0) openf1_timeout_seconds: float = Field(default=15.0, gt=0) @field_validator("app_log_level") @classmethod def normalize_log_level(cls, value: str) -> str: normalized = value.strip().upper() allowed = {"CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"} if normalized not in allowed: raise ValueError(f"APP_LOG_LEVEL must be one of {sorted(allowed)}") return normalized @field_validator("model_path", "model_schema_path", mode="after") @classmethod def resolve_project_path(cls, value: Path) -> Path: if value.is_absolute(): return value.resolve() return (PROJECT_ROOT / value).resolve() @lru_cache(maxsize=1) def get_settings() -> Settings: return Settings()