"""This module provides global application settings.

All settings are read from environment variables, but defaults are provided below
if the respective envvar is unset.
"""

import os
from urllib.parse import quote_plus as url_encode
from functools import lru_cache

from pydantic import BaseSettings


class Settings(BaseSettings):
    """Contains application-specific configuration values.

    Reads the values from environment variables and falls back to default values
    if the corresponding environment variable is unset.
    """

    app_name: str = os.getenv("APP_NAME", "TodoApp")
    app_version: str = os.getenv("APP_VERSION", "Unspecified")

    contact_name: str = os.getenv("CONTACT_NAME", "TodoApp Development Team")
    contact_email: str = os.getenv("CONTACT_EMAIL", "admin@example.com")
    contact_url: str = os.getenv("CONTACT_URL", "https://www.example.com")

    # Debug mode has the following effects:
    #   - logs SQL operations
    debug_mode: bool = False
    if os.getenv("DEBUG_MODE", "false").lower() == "true":
        debug_mode = True

    pg_hostname = url_encode(os.getenv("POSTGRES_HOST", "todo-db"))
    pg_port = os.getenv("POSTGRES_PORT", "5432")
    pg_dbname = os.getenv("POSTGRES_DB", "todo")
    pg_user = url_encode(os.getenv("POSTGRES_USER", "todo"))
    # XXX Change the database password to a random string of at least 16 characters
    pg_password = url_encode(os.getenv("POSTGRES_PASSWORD", "todo"))

    # XXX Change the JWT secret to a random string of at least 32 characters
    # The JWT secret is used to verify JWT signatures
    jwt_secret = os.getenv("JWT_SECRET", "todo")
    # Duration in seconds for how long newly created JWTs are valid
    jwt_expiration_time = int(os.getenv("JWT_EXPIRATION_TIME", "172800"))


@lru_cache
def get_settings() -> Settings:
    """Creates the settings once and returns a cached version on subsequent requests."""

    return Settings()
