from functools import lru_cache

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """
    Application settings loaded from environment variables.

    For production deployment with multiple ports/workers:
    - Set WORKERS=4 for 4 workers per port
    - Set DEBUG=False to disable docs and verbose logging
    - Set ALLOWED_ORIGINS to restrict CORS
    - Configure proper REDIS_URL and database credentials
    """

    # Application
    PROJECT_TITLE: str = "Agent Processing Server"
    PROJECT_URL: str = "0.0.0.0"
    PROJECT_PORT: int = 8000
    RELOAD: bool = False
    DEBUG: bool = False
    WORKERS: int = 4  # Default 4 workers for production

    SECRET_KEY: str
    ALGORITHM: str

    # Database
    DB_HOST: str
    DB_PORT: int
    DB_NAME: str
    DB_USER: str
    DB_PASSWORD: str

    # Redis — set REDIS_URL in .env for non-local environments
    REDIS_URL: str = "redis://localhost:6379"

    # External APIs
    SYSTEM_BUILDER_API_URL: str = ""

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=True,
        extra="ignore",
    )


@lru_cache()
def get_settings() -> Settings:
    """
    Cached function to return the Settings instance.

    Using lru_cache ensures that settings are only read once, improving performance.
    """
    return Settings()


# Singleton settings instance for use throughout the project
settings_instance = get_settings()
