"""AIF Project Configuration"""
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import AliasChoices, Field, ValidationError


class Settings(BaseSettings):
    """Application Settings"""
    
    # Normbase persistence
    database_url: str = Field(
        validation_alias=AliasChoices("NORMBASE_DATABASE_URL", "DATABASE_URL")
    )
    
    # Normbase infra dependencies
    redis_url: str = Field(
        validation_alias=AliasChoices("NORMBASE_REDIS_URL", "REDIS_URL")
    )
    
    # Normbase vector store
    qdrant_url: str = Field(
        validation_alias=AliasChoices("NORMBASE_QDRANT_URL", "QDRANT_URL")
    )
    qdrant_collection: str = Field(
        validation_alias=AliasChoices("NORMBASE_QDRANT_COLLECTION", "QDRANT_COLLECTION")
    )
    qdrant_vector_size: int = Field(
        validation_alias=AliasChoices("NORMBASE_QDRANT_VECTOR_SIZE", "QDRANT_VECTOR_SIZE")
    )
    
    # Service listen/runtime
    api_host: str = Field(validation_alias=AliasChoices("NORMBASE_API_HOST", "API_HOST"))
    normbase_api_port: int = Field(validation_alias=AliasChoices("NORMBASE_API_PORT"))
    eda_api_port: int = Field(validation_alias=AliasChoices("EDA_API_PORT"))
    ui_port: int = Field(validation_alias=AliasChoices("UI_PORT"))
    api_debug: bool = Field(
        validation_alias=AliasChoices("NORMBASE_API_DEBUG", "API_DEBUG")
    )

    # Service discovery URLs
    normbase_base_url: str = Field(validation_alias=AliasChoices("NORMBASE_BASE_URL"))
    eda_base_url: str = Field(validation_alias=AliasChoices("EDA_BASE_URL"))
    ui_base_url: str = Field(validation_alias=AliasChoices("UI_BASE_URL"))

    # Shared security (read-only status exposure / downstream checks)
    aif_internal_service_token: str | None = Field(
        default=None,
        validation_alias=AliasChoices("AIF_INTERNAL_SERVICE_TOKEN"),
    )
    aif_api_key_salt: str | None = Field(
        default=None,
        validation_alias=AliasChoices("AIF_API_KEY_SALT"),
    )

    # Retrieval cache
    retrieve_cache_enabled: bool = Field(
        validation_alias=AliasChoices(
            "NORMBASE_RETRIEVE_CACHE_ENABLED", "RETRIEVE_CACHE_ENABLED"
        )
    )
    retrieve_cache_ttl_seconds: int = Field(
        validation_alias=AliasChoices(
            "NORMBASE_RETRIEVE_CACHE_TTL_SECONDS", "RETRIEVE_CACHE_TTL_SECONDS"
        )
    )
    retrieve_cache_prefix: str = Field(
        validation_alias=AliasChoices(
            "NORMBASE_RETRIEVE_CACHE_PREFIX", "RETRIEVE_CACHE_PREFIX"
        )
    )

    # Norm extraction (process JSON + uploads); paths relative to CWD unless absolute
    extraction_artifact_dir: str = Field(
        default="data/normbase/extraction/artifacts",
        validation_alias=AliasChoices(
            "NORMBASE_EXTRACTION_ARTIFACT_DIR", "EXTRACTION_ARTIFACT_DIR"
        ),
    )
    extraction_upload_dir: str = Field(
        default="data/normbase/extraction/uploads",
        validation_alias=AliasChoices(
            "NORMBASE_EXTRACTION_UPLOAD_DIR", "EXTRACTION_UPLOAD_DIR"
        ),
    )
    extraction_artifact_max_bytes: int = Field(
        default=33_554_432,  # 32 MiB
        ge=1024,
        validation_alias=AliasChoices(
            "NORMBASE_EXTRACTION_ARTIFACT_MAX_BYTES", "EXTRACTION_ARTIFACT_MAX_BYTES"
        ),
    )
    extraction_upload_max_bytes: int = Field(
        default=104_857_600,  # 100 MiB
        ge=1024,
        validation_alias=AliasChoices(
            "NORMBASE_EXTRACTION_UPLOAD_MAX_BYTES", "EXTRACTION_UPLOAD_MAX_BYTES"
        ),
    )
    extraction_upload_public_base_url: str | None = Field(
        default=None,
        validation_alias=AliasChoices(
            "NORMBASE_EXTRACTION_UPLOAD_PUBLIC_BASE_URL",
            "EXTRACTION_UPLOAD_PUBLIC_BASE_URL",
        ),
        description="Optional HTTPS base (no trailing slash) prepended to storage_relative_path for source_file_url.",
    )
    # LLM chunking / completion budgets for norm extraction live in ``norm_extractor.settings``
    # (env: NORMBASE_EXTRACTION_* or NORM_EXTRACTOR_* — see norm_extractor/settings.py and .env.example.normbase).

    model_config = SettingsConfigDict(
        env_file=".env",
        extra="allow",
    )

def _load_settings() -> Settings:
    try:
        return Settings()
    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 environment variables: "
                + ", ".join(missing)
            ) from exc
        raise RuntimeError(f"Invalid environment configuration: {exc}") from exc


settings = _load_settings()
