"""Runtime settings. Values come from the environment (.app.env), never code."""

from __future__ import annotations

from functools import lru_cache
from pathlib import Path

from pydantic_settings import BaseSettings, SettingsConfigDict

_VERSION_FILE = Path(__file__).resolve().parent.parent / "VERSION"


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="CP_", extra="ignore")

    database_url: str = "postgresql+psycopg://coachpapa:coachpapa@db:5432/coachpapa"
    media_root: Path = Path("/data/media")
    app_env: str = "production"
    ticket_prefix: str = "CP"

    # Voice-memo transcription. The key is supplied via .app.env (mode 660);
    # it is never logged, echoed, or included in an error response.
    gemini_api_key: str = ""
    transcription_provider: str = "gemini"
    transcribe_model: str = "gemini-2.5-flash"

    @property
    def version(self) -> str:
        try:
            return _VERSION_FILE.read_text(encoding="utf-8").strip()
        except OSError:
            return "unknown"

    @property
    def has_gemini_key(self) -> bool:
        """True only for a real key.

        The server's credential workflow stages secrets as
        `REPLACE_WITH_<NAME>` placeholders for a human to fill in their own
        shell. A placeholder is a non-empty string, so a naive truthiness check
        reports "configured" and the feature fails at first use instead of
        degrading cleanly. Treat any unfilled placeholder as absent.
        """
        key = (self.gemini_api_key or "").strip()
        return bool(key) and not key.startswith("REPLACE_WITH_")


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