import os

from pydantic import BaseModel


class DatabaseConfig(BaseModel):
    """Configuration for the PostgreSQL connection."""

    dsn: str  # postgresql+asyncpg://user:pass@host:port/dbname
    pool_size: int = 5
    max_overflow: int = 10
    echo: bool = False
    batch_size: int = 100

    @classmethod
    def from_env(cls) -> "DatabaseConfig":
        """Build config from environment variables.

        Reads:
        - SESSION_HUB_DSN (required) — full SQLAlchemy DSN
        - SESSION_HUB_POOL_SIZE (optional, default 5)
        - SESSION_HUB_ECHO (optional, default false)
        - SESSION_HUB_BATCH_SIZE (optional, default 100)
        """
        dsn = os.environ.get("SESSION_HUB_DSN")
        if not dsn:
            raise ValueError("SESSION_HUB_DSN is not set")
        return cls(
            dsn=dsn,
            pool_size=int(os.environ.get("SESSION_HUB_POOL_SIZE", "5")),
            echo=_env_bool("SESSION_HUB_ECHO", False),
            batch_size=int(os.environ.get("SESSION_HUB_BATCH_SIZE", "100")),
        )

    @classmethod
    def from_url(
        cls,
        host: str = "localhost",
        port: int = 5432,
        database: str = "session_hub",
        user: str = "session_hub",
        password: str = "",
    ) -> "DatabaseConfig":
        """Build config from individual URL components."""
        dsn = f"postgresql+asyncpg://{user}:{password}@{host}:{port}/{database}"
        return cls(dsn=dsn)


class EmbeddingConfig(BaseModel):
    """Configuration for the embedding service (via OpenRouter)."""

    api_key: str  # OpenRouter API key (from OPENROUTER_API_KEY env)
    base_url: str = "https://openrouter.ai/api/v1"
    model: str = "openai/text-embedding-3-small"
    dimensions: int = 1536
    batch_size: int = 100  # max texts per API call
    max_tokens_per_text: int = 8000  # truncate long content

    @classmethod
    def from_env(cls) -> "EmbeddingConfig":
        """Build config from environment variables.

        Reads:
        - OPENROUTER_API_KEY (required)
        - SESSION_HUB_EMBEDDING_MODEL (optional, default openai/text-embedding-3-small)
        - SESSION_HUB_EMBEDDING_BATCH_SIZE (optional, default 100)
        - SESSION_HUB_EMBEDDING_BASE_URL (optional, default https://openrouter.ai/api/v1)
        """
        api_key = os.environ.get("OPENROUTER_API_KEY")
        if not api_key:
            raise ValueError("OPENROUTER_API_KEY is not set")
        return cls(
            api_key=api_key,
            model=os.environ.get("SESSION_HUB_EMBEDDING_MODEL", "openai/text-embedding-3-small"),
            batch_size=int(os.environ.get("SESSION_HUB_EMBEDDING_BATCH_SIZE", "100")),
            base_url=os.environ.get(
                "SESSION_HUB_EMBEDDING_BASE_URL", "https://openrouter.ai/api/v1"
            ),
        )


def _env_bool(name: str, default: bool) -> bool:
    value = os.environ.get(name)
    if value is None:
        return default
    return value.strip().lower() in {"1", "true", "yes", "on"}
