"""EDA Agent service configuration."""
from pydantic import AliasChoices, Field, ValidationError
from pydantic_settings import BaseSettings


class EDASettings(BaseSettings):
    """Settings dedicated to EDA Agent service runtime."""

    eda_database_url: str = Field(
        validation_alias=AliasChoices("EDA_DATABASE_URL", "DATABASE_URL")
    )
    eda_api_host: str = Field(
        validation_alias=AliasChoices("EDA_API_HOST", "API_HOST")
    )
    eda_api_port: int = Field(validation_alias=AliasChoices("EDA_API_PORT"))
    eda_api_debug: bool = Field(
        validation_alias=AliasChoices("EDA_API_DEBUG", "API_DEBUG")
    )
    eda_normbase_base_url: str = Field(
        validation_alias=AliasChoices("EDA_NORMBASE_BASE_URL", "NORMBASE_BASE_URL")
    )
    eda_normbase_retrieve_timeout_seconds: int = Field(
        validation_alias=AliasChoices(
            "EDA_NORMBASE_RETRIEVE_TIMEOUT_SECONDS",
            "NORMBASE_RETRIEVE_TIMEOUT_SECONDS",
        )
    )

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


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


settings = _load_settings()
