# app/vector.py
from __future__ import annotations

from langchain_community.embeddings import FastEmbedEmbeddings

DEFAULT_EMBED_MODEL = "nomic-embed-text-v1.5"

# We try some common nomic variants then fall back to supported list.
DEFAULT_EMBED_CANDIDATES = [
    DEFAULT_EMBED_MODEL,
    "nomic-ai/nomic-embed-text-v1.5",
    "nomic-embed-text",
    "nomic-ai/nomic-embed-text",
]


def _pick_supported_fastembed_model(preferred: str | None) -> str:
    candidates: list[str] = []
    if preferred:
        candidates.append(preferred.strip())
    for c in DEFAULT_EMBED_CANDIDATES:
        if c not in candidates:
            candidates.append(c)

    # Try candidates
    for name in candidates:
        try:
            _ = FastEmbedEmbeddings(model_name=name)
            return name
        except Exception:
            pass

    # Ask fastembed for supported models and pick one
    try:
        from fastembed import TextEmbedding

        supported = TextEmbedding.list_supported_models()

        prefer_keys = ["nomic", "bge", "e5", "gte", "minilm", "all-minilm"]
        for key in prefer_keys:
            for m in supported:
                if key in (m or "").lower():
                    return m

        if supported:
            return supported[0]
    except Exception:
        pass

    raise ValueError(
        "No supported FastEmbed embedding model found. "
        "Run: python -c \"from fastembed import TextEmbedding; print(TextEmbedding.list_supported_models())\""
    )


def make_embeddings(*, embedding_model: str | None = None) -> FastEmbedEmbeddings:
    chosen = _pick_supported_fastembed_model(embedding_model or DEFAULT_EMBED_MODEL)
    return FastEmbedEmbeddings(model_name=chosen)
