from functools import lru_cache

from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


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

    database_url: str
    s3_endpoint_url: str
    s3_bucket_name: str
    s3_access_key_id: str
    s3_secret_access_key: str
    s3_region: str = "us-east-1"
    api_base_url: str = "http://localhost:8000"
    s3_public_base_url: str | None = None
    max_upload_bytes: int = 52_428_800  # 50 MiB
    jwt_secret_key: str
    jwt_expiry_seconds: int = 86400
    owner_username: str
    owner_password: str
    login_max_failures: int = 5
    login_window_seconds: int = 300
    login_cooldown_seconds: int = 900
    login_trusted_proxy_ips: str = ""
    api_docs_enabled: bool = True

    @field_validator("api_docs_enabled", mode="before")
    @classmethod
    def coerce_docs_enabled(cls, v):
        if isinstance(v, bool):
            return v
        try:
            from pydantic import TypeAdapter

            return TypeAdapter(bool).validate_python(v)
        except Exception:
            return True


@lru_cache
def get_settings() -> Settings:
    return Settings()
