from functools import lru_cache

from pydantic import computed_field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    app_name: str = "Restaurant Booking SaaS"
    app_environment: str = "development"
    database_url: str = "postgresql+psycopg2://postgres:postgres@localhost:5432/restaurant_booking"
    backend_cors_origins: str = "http://localhost:3000"
    public_base_url: str = "http://localhost:8000"
    assistant_api_base_url: str = "http://backend-hub:8000"
    llm_proxy_internal_token: str | None = None
    assistant_timeout_seconds: float = 30.0
    assistant_history_limit: int = 12
    assistant_reply_max_chars: int = 1500
    whatsapp_access_token: str | None = None
    whatsapp_phone_number_id: str | None = None
    whatsapp_verify_token: str | None = None
    whatsapp_app_secret: str | None = None
    whatsapp_graph_api_version: str = "v21.0"
    whatsapp_api_base_url: str = "https://graph.facebook.com"
    whatsapp_timeout_seconds: float = 15.0
    seed_demo_enabled: bool = False

    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]:
        cleaned = self.backend_cors_origins.strip()
        if cleaned.startswith("[") and cleaned.endswith("]"):
            inner = cleaned[1:-1]
            return [item.strip().strip('"').strip("'") for item in inner.split(",") if item.strip()]
        return [item.strip() for item in cleaned.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 not (self.llm_proxy_internal_token or "").strip():
            raise RuntimeError("LLM_PROXY_INTERNAL_TOKEN e' obbligatorio in produzione")


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