"""Dashboard runtime configuration."""
from __future__ import annotations

from pydantic import AliasChoices, Field, ValidationError
from pydantic_settings import BaseSettings


class DashboardSettings(BaseSettings):
    host: str = Field(default="0.0.0.0", alias="DASHBOARD_HOST")
    port: int = Field(default=8010, alias="DASHBOARD_PORT")
    debug: bool = Field(default=False, alias="DASHBOARD_DEBUG")
    # Keep base URLs required (no defaults).
    normbase_base_url: str = Field(alias="NORMBASE_BASE_URL")
    eda_base_url: str = Field(alias="EDA_BASE_URL")
    mcp_base_url: str = Field(alias="MCP_BASE_URL")
    mcp_audit_log: str = Field(default="", alias="AIF_MCP_AUDIT_LOG")
    aif_internal_service_token: str = Field(default="", alias="AIF_INTERNAL_SERVICE_TOKEN")
    aif_api_key_salt: str = Field(default="", alias="AIF_API_KEY_SALT")

    # Neo4j (optional; used by dashboard graph viewer)
    neo4j_bolt_uri: str = Field(default="", alias="NEO4J_BOLT_URI")
    neo4j_user: str = Field(default="", alias="NEO4J_USER")
    neo4j_password: str = Field(default="", alias="NEO4J_PASSWORD")

    # Normbase extraction calls LLM (possibly many chunks); read timeout must exceed worst case.
    normbase_extraction_read_timeout_seconds: float = Field(
        default=900.0,
        ge=60.0,
        le=7200.0,
        validation_alias=AliasChoices(
            "DASHBOARD_NORMBASE_EXTRACTION_READ_TIMEOUT_SECONDS",
            "DASHBOARD_EXTRACTION_READ_TIMEOUT_SECONDS",
        ),
    )

    class Config:
        env_file = ".env"
        extra = "allow"


def _load_settings() -> DashboardSettings:
    try:
        settings = DashboardSettings()
    except ValidationError as exc:
        missing = [
            ".".join(str(part) for part in err.get("loc", []))
            for err in exc.errors()
            if err.get("type") == "missing"
        ]
        if missing:
            raise RuntimeError(
                "Missing required environment variables: " + ", ".join(missing)
            ) from exc
        raise RuntimeError(f"Invalid dashboard environment configuration: {exc}") from exc

    settings.normbase_base_url = settings.normbase_base_url.rstrip("/")
    settings.eda_base_url = settings.eda_base_url.rstrip("/")
    settings.mcp_base_url = settings.mcp_base_url.rstrip("/")
    settings.mcp_audit_log = settings.mcp_audit_log.strip()
    settings.aif_internal_service_token = settings.aif_internal_service_token.strip()
    settings.aif_api_key_salt = settings.aif_api_key_salt.strip()
    settings.neo4j_bolt_uri = settings.neo4j_bolt_uri.strip()
    settings.neo4j_user = settings.neo4j_user.strip()
    settings.neo4j_password = settings.neo4j_password.strip()
    return settings


settings = _load_settings()

