"""Hospitality Platform Service settings."""
from __future__ import annotations

from functools import lru_cache
from typing import Literal

from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
    )

    environment: Literal["development", "staging", "production", "test"] = "development"
    debug: bool = True
    log_level: str = "INFO"
    service_name: str = Field(
        default="hospitality-service", validation_alias="HOSPITALITY_SERVICE_NAME"
    )
    api_v1_prefix: str = "/api/v1"

    database_url: str = Field(
        default="postgresql+asyncpg://superapp:superapp_password@localhost:5432/hospitality_db",
        validation_alias="HOSPITALITY_DATABASE_URL",
    )
    database_url_sync: str = Field(
        default="postgresql+psycopg://superapp:superapp_password@localhost:5432/hospitality_db",
        validation_alias="HOSPITALITY_DATABASE_URL_SYNC",
    )

    core_service_url: str = Field(
        default="http://localhost:8000", validation_alias="CORE_SERVICE_URL"
    )

    keycloak_enabled: bool = True
    keycloak_server_url: str = Field(
        default="http://localhost:8080", validation_alias="KEYCLOAK_SERVER_URL"
    )
    keycloak_public_url: str = Field(default="", validation_alias="KEYCLOAK_PUBLIC_URL")
    keycloak_realm: str = Field(default="superapp", validation_alias="KEYCLOAK_REALM")

    jwt_algorithm: str = "RS256"
    jwt_audience: str = "account"
    jwt_verify_signature: bool = True
    auth_required: bool = True

    cors_origins: str = Field(
        default="http://localhost:3000,http://127.0.0.1:3000",
        validation_alias="CORS_ORIGINS",
    )

    @property
    def keycloak_public_base(self) -> str:
        return (self.keycloak_public_url or self.keycloak_server_url).rstrip("/")

    @property
    def keycloak_public_realm_url(self) -> str:
        return f"{self.keycloak_public_base}/realms/{self.keycloak_realm}"

    @property
    def cors_origin_list(self) -> list[str]:
        return [o.strip() for o in self.cors_origins.split(",") if o.strip()]


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


settings = get_settings()
