# src/fmatch/shared/settings.py
from pydantic_settings import BaseSettings
from typing import Literal, Optional
from functools import lru_cache


class AppSettings(BaseSettings):
    """
    Defines application-wide settings, loaded from environment variables.
    Pydantic handles the validation and type casting automatically.
    """

    # Storage Configuration
    STORAGE_BACKEND: Literal["local", "s3"] = "local"
    S3_BUCKET_NAME: str = "foundry-match-uploads"
    S3_ENDPOINT_URL: Optional[str] = None
    S3_ACCESS_KEY_ID: Optional[str] = None
    S3_SECRET_ACCESS_KEY: Optional[str] = None

    # Database Configuration
    DATABASE_URL: str = (
        "postgresql+asyncpg://foundrymatch:foundrymatch@localhost:5432/foundrymatch"
    )

    # Redis Configuration
    REDIS_URL: str = "redis://localhost:6379"

    # Authentication Settings
    AUTH_ISSUER: str = "https://your-auth-provider.com/"
    AUTH_AUDIENCE: str = "https://api.foundrymatch.com"
    # Optional Clerk overrides (if provided, they take precedence)
    CLERK_PUBLISHABLE_KEY: Optional[str] = None  # Client-side key for JavaScript SDK
    CLERK_SECRET_KEY: Optional[str] = None  # Server-side key for backend validation
    CLERK_ISSUER: Optional[str] = None
    CLERK_AUDIENCE: Optional[str] = None
    CLERK_JWKS_URL: Optional[str] = None
    JWT_SECRET_KEY: Optional[str] = None
    JWT_ALGORITHM: str = "HS256"
    JWT_EXPIRATION_HOURS: int = 24

    # API Configuration
    API_VERSION: str = "1.0.0"
    CORS_ORIGINS: str = "http://localhost:3000,http://localhost:3001,http://localhost:8080,http://localhost:5173,http://127.0.0.1:5173"

    # Processing Limits
    SYNC_ROW_LIMIT: int = 10000
    MAX_ROWS_DEFAULT: int = 1000000
    MAX_SYNC_MEMORY_MB: int = 100
    MAX_UPLOAD_SIZE: int = 104857600  # 100MB
    MAX_STRING_DATA_MB: int = 100

    # Matching Defaults
    DEFAULT_DEDUPE_THRESHOLD: int = 85
    DEFAULT_MATCH_THRESHOLD: int = 80
    DEFAULT_BLOCK_KEY_LENGTH: int = 3
    DEFAULT_DUP_BLOCK_LIMIT: int = 2000

    # Rate Limiting
    RATE_LIMIT_SIMPLE_MATCH: str = "100/hour"
    RATE_LIMIT_STATUS: str = "1000/hour"
    RATE_LIMIT_RESULTS: str = "500/hour"

    # Webhook Settings
    WEBHOOK_TIMEOUT: int = 30
    REQUIRE_HTTPS_WEBHOOKS: bool = False

    # Security Settings
    FORBIDDEN_HOSTS: set = {
        "localhost",
        "127.0.0.1",
        "0.0.0.0",
        "169.254.169.254",
        "::1",
        "[::1]",
        "metadata.google.internal",
    }
    FORBIDDEN_URL_PATTERNS: list = ["metadata", "userdata", ".internal"]

    # Documentation/Support
    DOCS_URL: str = "https://docs.foundrymatch.com/ipaas"
    SUPPORT_EMAIL: str = "support@foundrymatch.com"

    # Logging
    LOG_LEVEL: str = "INFO"
    LOG_FORMAT: str = "%(asctime)s %(levelname)8s [%(name)s] %(message)s"

    # Environment
    ENV: str = "development"

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        extra = "allow"  # Allow extra fields from environment


@lru_cache()
def get_settings() -> AppSettings:
    """
    Returns a cached instance of the application settings.
    The settings are only loaded the first time this function is called.
    """
    return AppSettings()
