from functools import lru_cache

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
    )

    # ── Application ────────────────────────────────────────────────────────────
    app_name: str = "Campus Safe API"
    app_version: str = "1.0.0"
    debug: bool = False
    environment: str = "development"
    api_v1_prefix: str = "/api/v1"
    guest_mode_enabled: bool = True
    guest_merge_time_window_hours: int = 24

    # ── CORS ───────────────────────────────────────────────────────────────────
    # Comma-separated list parsed by pydantic automatically when field is list[str]
    allowed_origins: list[str] = ["http://localhost:3000", "http://localhost:8080"]

    # ── Database ───────────────────────────────────────────────────────────────
    database_url: str = "postgresql+psycopg://root:password@localhost:5432/campus_safe"

    # ── JWT ────────────────────────────────────────────────────────────────────
    jwt_secret_key: str = "CHANGE_ME_IN_PRODUCTION"
    jwt_algorithm: str = "HS256"
    access_token_expire_minutes: int = 60
    refresh_token_expire_days: int = 7

    # ── File server (local disk storage) ──────────────────────────────────────
    files_server_url: str = "http://localhost:9100"
    files_server_api_key: str = ""
    max_file_size_mb: int = 10
    upload_dir: str = "uploads"

    # ── Appwrite (resources storage) ──────────────────────────────────────────
    appwrite_enabled: bool = False
    appwrite_endpoint: str = ""
    appwrite_project_id: str = ""
    appwrite_bucket_id: str = "resources"
    appwrite_api_key: str = ""
    resource_max_file_size_mb: int = 20
    resource_allowed_mime_types: list[str] = [
        "application/pdf",
        "image/jpeg",
        "image/png",
        "image/webp",
        "video/mp4",
    ]

    # ── Dev helpers ────────────────────────────────────────────────────────────
    # Set to False in production — manage schema with SQL scripts
    auto_create_tables: bool = True
    testing: bool = False

    # ── Logging ────────────────────────────────────────────────────────────────
    log_level: str = "INFO"


@lru_cache
def get_settings() -> Settings:
    return Settings()


settings: Settings = get_settings()
