"""Build an embedder from configuration."""

from __future__ import annotations

from legate.config import Settings, get_settings
from legate.rag.embeddings.base import Embedder, EmbeddingError
from legate.rag.embeddings.hashing import HashingEmbedder
from legate.rag.embeddings.openai import OpenAIEmbedder


def build_embedder(settings: Settings | None = None) -> Embedder:
    settings = settings or get_settings()
    provider = (settings.embedding_provider or "openai").lower()

    if provider == "hashing":
        return HashingEmbedder(
            dim=settings.embedding_dim, model=settings.embedding_model or "hashing-v1"
        )
    if provider == "openai":
        if not settings.llm_api_key:
            raise EmbeddingError("LLM_API_KEY is required for the openai embedding provider")
        return OpenAIEmbedder(
            api_key=settings.llm_api_key,
            model=settings.embedding_model,
            base_url=settings.openai_base_url,
        )

    raise EmbeddingError(f"unsupported embedding provider '{provider}'; available: openai, hashing")
