from functools import lru_cache

from pydantic import computed_field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    app_name: str = "Hospitality Orders Module"
    app_environment: str = "development"
    database_url: str = "postgresql+psycopg2://postgres:postgres@ordini-db:5432/orders_management"
    backend_cors_origins: str = "http://localhost:3300,http://localhost:3000"
    public_base_url: str = "http://localhost:8200"
    frontend_public_url: str = "http://localhost:3300"
    admin_password: str = ""
    api_token: str = ""
    default_staff: str = "club"
    tenancy_registry_database: str = "/data/platform_registry.sqlite3"
    tenancy_session_duration_hours: int = 168
    push_vapid_private_key_file: str = "/data/push-vapid-private.pem"
    push_vapid_subject: str = "mailto:admin@powerup.cool"
    safety_stock_notification_poll_seconds: int = 900

    model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", case_sensitive=False)

    @computed_field  # type: ignore[prop-decorator]
    @property
    def cors_origins_list(self) -> list[str]:
        return [item.strip() for item in self.backend_cors_origins.split(",") if item.strip()]

    @computed_field  # type: ignore[prop-decorator]
    @property
    def is_production(self) -> bool:
        return self.app_environment.strip().lower() in {"prod", "production"}

    def validate_runtime(self) -> None:
        if not self.is_production:
            return
        if self.admin_password in {"", "club"}:
            raise RuntimeError("ORDINI_ADMIN_PASSWORD deve essere impostata a un valore non dimostrativo in produzione")
        if self.api_token in {"", "ordini-demo-token"}:
            raise RuntimeError("ORDINI_API_TOKEN deve essere impostato a un valore non dimostrativo in produzione")


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