import os
from typing import Any, Dict, Optional

from pydantic import BaseModel, Field, model_validator


class PGVectorConfig(BaseModel):
    dbname: str = Field(os.getenv("POSTGRES_DBNAME") or "postgres", description="Default name for the database")
    collection_name: str = Field(
        os.getenv("POSTGRES_COLLECTION_NAME") or "mem0x", description="Default name for the collection"
    )
    embedding_model_dims: Optional[int] = Field(768, description="Dimensions of the embedding model")
    user: Optional[str] = Field(os.getenv("POSTGRES_USER") or "guest", description="Database user")
    password: Optional[str] = Field(os.getenv("POSTGRES_PASSWORD") or None, description="Database password")
    host: Optional[str] = Field(os.getenv("POSTGRES_HOST") or None, description="Database host. Default is localhost")
    port: Optional[int] = Field(5432, description="Database port. Default is 5432")
    diskann: Optional[bool] = Field(True, description="Use diskann for approximate nearest neighbors search")
    hnsw: Optional[bool] = Field(False, description="Use hnsw for faster search")

    @model_validator(mode="before")
    @classmethod
    def validate_extra_fields(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        allowed_fields = set(cls.model_fields.keys())
        input_fields = set(values.keys())
        extra_fields = input_fields - allowed_fields
        if extra_fields:
            raise ValueError(
                f"Extra fields not allowed: {', '.join(extra_fields)}. Please input only the following fields: {', '.join(allowed_fields)}"
            )
        return values
