"""AIF Project Configuration"""
from pydantic_settings import BaseSettings
from pydantic import AliasChoices, Field, ValidationError
from typing import Dict, Any


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")
    )
    
    # Normbase LLM provider
    llm_provider: str = Field(
        validation_alias=AliasChoices("NORMBASE_LLM_PROVIDER", "LLM_PROVIDER")
    )
    llm_api_key: str = Field(
        validation_alias=AliasChoices("NORMBASE_LLM_API_KEY", "LLM_API_KEY")
    )
    llm_model: str = Field(
        validation_alias=AliasChoices("NORMBASE_LLM_MODEL", "LLM_MODEL")
    )
    llm_embedding_model: str = Field(
        validation_alias=AliasChoices(
            "NORMBASE_LLM_EMBEDDING_MODEL", "LLM_EMBEDDING_MODEL"
        )
    )
    llm_base_url: str | None = Field(
        default=None,
        validation_alias=AliasChoices("NORMBASE_LLM_BASE_URL", "LLM_BASE_URL"),
    )
    
    # 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"))

    # 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"
        )
    )
    
    class Config:
        env_file = ".env"
        extra = "allow"

    def get_llm_provider_config(self) -> Dict[str, Any]:
        """Build and validate provider config for LLMProviderFactory."""
        provider_block: Dict[str, Any] = {
            "api_key": self.llm_api_key,
            "model": self.llm_model,
            "embedding_model": self.llm_embedding_model,
        }
        if self.llm_base_url:
            provider_block["base_url"] = self.llm_base_url

        config = {self.llm_provider: provider_block}
        return config


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()
