from functools import lru_cache

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Application configuration loaded from environment / .env file."""

    db_host: str = "localhost"
    db_port: int = 3306
    db_user: str = "yatra"
    db_password: str = "yatra"
    db_name: str = "cycleyatra"

    cors_origins: str = "http://localhost:3000,http://localhost:5173"

    api_host: str = "0.0.0.0"
    api_port: int = 8000

    # --- Email / SMTP (provider-agnostic: Gmail, SendGrid, SES, Mailgun, ...) ---
    mail_enabled: bool = False  # leave False in dev/CI so missing SMTP creds don't error
    smtp_host: str = "localhost"
    smtp_port: int = 587
    smtp_user: str = ""
    smtp_password: str = ""
    smtp_use_tls: bool = True  # STARTTLS on port 587; set use_ssl + port 465 for implicit SSL
    smtp_use_ssl: bool = False

    mail_from: str = "no-reply@cycleyatra.org"
    mail_from_name: str = "CycleYatra 2026"

    # Where inbound contact / sponsorship submissions are delivered (comma-separated).
    contact_recipients: str = ""
    sponsorship_recipients: str = ""

    # Linked in the sponsorship auto-reply ("Secure Sponsorship Deck").
    sponsor_deck_url: str = ""

    # --- Admin auth (JWT) ---
    jwt_secret: str = "CHANGE_ME_TO_A_LONG_RANDOM_SECRET"
    jwt_algorithm: str = "HS256"
    access_token_expire_minutes: int = 60 * 12  # 12 hours

    # Auto-seeded superadmin on startup so the first login is possible.
    admin_bootstrap_email: str = ""
    admin_bootstrap_password: str = ""
    admin_bootstrap_name: str = "Super Admin"

    # --- Cloudinary (gallery image hosting) ---
    cloudinary_cloud_name: str = ""
    cloudinary_api_key: str = ""
    cloudinary_api_secret: str = ""
    # Folder all gallery uploads land in, so they're easy to find in the console.
    cloudinary_folder: str = "cycleyatra/gallery"
    # Reject uploads larger than this (bytes). Default 10 MB.
    max_upload_bytes: int = 10 * 1024 * 1024

    model_config = SettingsConfigDict(env_file=".env", extra="ignore")

    @property
    def database_url(self) -> str:
        return (
            f"mysql+pymysql://{self.db_user}:{self.db_password}"
            f"@{self.db_host}:{self.db_port}/{self.db_name}?charset=utf8mb4"
        )

    @property
    def cloudinary_configured(self) -> bool:
        return bool(
            self.cloudinary_cloud_name
            and self.cloudinary_api_key
            and self.cloudinary_api_secret
        )

    @property
    def cors_origins_list(self) -> list[str]:
        return [origin.strip() for origin in self.cors_origins.split(",") if origin.strip()]

    @property
    def contact_recipients_list(self) -> list[str]:
        return [a.strip() for a in self.contact_recipients.split(",") if a.strip()]

    @property
    def sponsorship_recipients_list(self) -> list[str]:
        return [a.strip() for a in self.sponsorship_recipients.split(",") if a.strip()]


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