"""Application configuration via Pydantic Settings."""

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    """Application settings loaded from environment variables."""

    # Database
    database_url: str = "postgresql+asyncpg://dsol:dsol_dev_password@localhost:5432/dsol"

    # Redis - single URL for local (redis://) or Azure (rediss://)
    redis_url: str = "redis://localhost:6379"

    # Milvus
    milvus_host: str = "localhost"
    milvus_port: int = 19530
    milvus_collection: str = "textiq_records"

    # Azure OpenAI
    azure_openai_api_key: str = ""
    azure_openai_endpoint: str = ""
    azure_openai_api_version: str = "2024-02-15-preview"
    azure_openai_deployment: str = "gpt-4o"
    azure_openai_embedding_deployment: str = "text-embedding-3-large"
    azure_openai_temperature: float = 0.0
    azure_openai_max_tokens: int = 4096

    # LLM Provider Selection (azure_openai | vllm)
    llm_provider: str = "azure_openai"
    llm_base_url: str = ""
    llm_api_key: str = ""
    llm_model_name: str = ""

    # Embedding Provider Selection (azure_openai | vllm)
    embedding_provider: str = "azure_openai"
    embedding_base_url: str = ""
    embedding_api_key: str = ""
    embedding_model_name: str = ""
    embedding_dimensions: int = 3072
    # Max input tokens accepted by the embedding model (cl100k_base for OpenAI/Azure).
    # text-embedding-3-large/-small/-ada-002 = 8191. Used as hard limit when chunking
    # atomic units (e.g., mermaid diagrams) that must embed as a single vector.
    embedding_model_context_tokens: int = 8191

    # API Configuration
    log_level: str = "INFO"
    api_rate_limit: int = 60
    max_upload_size_mb: int = 50

    # Semantic Tagging
    tag_batch_size: int = 20
    tag_auto_approve_threshold: float = 0.95

    # LLM Concurrency (max parallel LLM requests per task)
    llm_concurrency: int = 10

    # SeaweedFS image storage
    image_bucket: str = "textiq-images"

    # Upload endpoint
    upload_bucket: str = "source-files"
    max_filename_length: int = 255

    # Docstore
    docstore_namespace: str = "hierarchical"
    docstore_table: str = "hierarchical_nodes"

    # Pipeline events (DE → UPA via Redis pub/sub)
    pipeline_events_enabled: bool = False
    pipeline_event_channel_prefix: str = "pipeline"

    # HMAC verification
    hmac_key_ring: str = ""
    hmac_key_ring_file: str = "/vault/secrets/hmac-key-ring.json"
    hmac_timestamp_tolerance: int = 30

    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",  # Ignore extra fields
    )

    @property
    def sync_database_url(self) -> str:
        """Return synchronous database URL for Alembic migrations."""
        return self.database_url.replace("+asyncpg", "+psycopg2")


# Global settings instance
settings = Settings()
