"""Server configuration via pydantic-settings."""

from __future__ import annotations

from pathlib import Path
from functools import lru_cache

from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    """Server settings, loaded from environment variables or .env file."""

    # Database
    database_url: str = "sqlite+aiosqlite:///opt/kredo/data/kredo_drift.db"
    database_echo: bool = False

    # Service identity
    service_key_path: Path = Path.home() / ".config" / "kredo-drift" / "service.key"
    service_name: str = "kredo-drift-server"

    # Vectorization
    model_name: str = "all-MiniLM-L6-v2"

    # Auth
    api_key_length: int = 32  # 256-bit, hex-encoded to 64 chars

    # Self-registration API
    admin_key: str = ""  # KREDO_ADMIN_KEY env var
    prompt_secret: str = "kredo-drift-v0"  # KREDO_PROMPT_SECRET env var

    # Rate limiting
    rate_limit_per_minute: int = 60

    # CORS
    cors_origins: list[str] = ["https://aikredo.com", "http://localhost:3000"]

    # WHY periodic Merkle rebuild (not real-time): Rebuilding the tree on every
    # chain event is O(n log n) and would add latency to every test submission.
    # A 10-minute rebuild interval batches changes, keeping writes fast while
    # ensuring the global root is reasonably fresh. The event threshold (50)
    # triggers an early rebuild if many agents submit simultaneously.
    merkle_rebuild_interval_seconds: int = 600  # 10 minutes
    merkle_rebuild_event_threshold: int = 50

    model_config = {"env_prefix": "KREDO_", "env_file": ".env"}


@lru_cache
def get_settings() -> Settings:
    """Cached settings singleton."""
    return Settings()
