"""
ABOS Auth – Application Configuration
=====================================
Settings come from environment variables prefixed AUTH_ (or a local .env file). The two secrets,
AUTH_MASTER_KEY and AUTH_ADMIN_KEY, have no usable default: without them the service starts but
refuses to save the WhatsApp token, refuses admin calls and refuses to send codes.
"""

from pydantic_settings import BaseSettings, SettingsConfigDict

MIN_SECRET_LENGTH = 32


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

    app_name: str = "ABOS Auth"
    app_version: str = "1.0.0"

    # SQLite file holding clients (hashed keys), codes (hashed), settings and the event log.
    db_path: str = "data/auth.db"

    # Encrypts the saved WhatsApp access token and keys the code hashes. Changing it later makes the saved
    # token unreadable (it has to be saved again) and invalidates pending codes.
    master_key: str = ""
    # Shared secret the Aggie API sends (X-Admin-Key) to manage the service. Never given to a client system.
    admin_key: str = ""

    # Same Graph version the Aggie API uses for WhatsApp.
    graph_base: str = "https://graph.facebook.com/v20.0"
    send_timeout_seconds: float = 15.0

    otp_length: int = 6
    otp_ttl_seconds: int = 600
    otp_max_attempts: int = 5
    resend_cooldown_seconds: int = 30
    max_sends_per_phone_per_hour: int = 5
    default_rate_per_minute: int = 60

    # Codeless "send this message on WhatsApp" login (no template needed: the person writes first).
    link_ttl_seconds: int = 600
    link_retention_days: int = 30

    # The service sits behind Apache; the client address is the LAST X-Forwarded-For entry (the one Apache saw).
    trust_proxy: bool = True

    event_retention_days: int = 90
    request_retention_days: int = 30

    @property
    def master_key_ok(self) -> bool:
        return len(self.master_key) >= MIN_SECRET_LENGTH

    @property
    def admin_key_ok(self) -> bool:
        return len(self.admin_key) >= MIN_SECRET_LENGTH
