from __future__ import annotations

import logging
import os

try:
    from langchain_core.embeddings import Embeddings  # type: ignore
except Exception:  # pragma: no cover
    class Embeddings:  # type: ignore
        def embed_documents(self, texts):
            raise NotImplementedError

        def embed_query(self, text):
            raise NotImplementedError


class SimpleEmbeddings(Embeddings):
    """Deterministic local embeddings (26 chars frequency)."""

    def _vector(self, text: str):
        counts = [0.0] * 26
        total = 0
        for ch in text.lower():
            if "a" <= ch <= "z":
                counts[ord(ch) - ord("a")] += 1.0
                total += 1
        if total:
            counts = [c / total for c in counts]
        return counts

    def embed_documents(self, texts):
        return [self._vector(t or "") for t in texts]

    def embed_query(self, text):
        return self._vector(text or "")


def get_embeddings(backend: str = "auto"):
    """
    Resolve embeddings backend.
    - `simple`: deterministic local embeddings
    - `hf`: HuggingFace embeddings
    - `auto`: env MAMA_EMBEDDINGS or fallback to `simple`
    """
    selected = backend
    if backend == "auto":
        selected = os.environ.get("MAMA_EMBEDDINGS", "simple").lower()

    if selected == "simple":
        return SimpleEmbeddings()

    if selected in {"hf", "huggingface"}:
        try:
            from langchain_community.embeddings import HuggingFaceEmbeddings  # type: ignore

            return HuggingFaceEmbeddings()
        except Exception as exc:  # pragma: no cover
            logging.warning("HuggingFace embeddings unavailable, fallback to simple: %s", exc)
            return SimpleEmbeddings()

    if selected in {"ollama", "local_ollama"}:
        try:
            from langchain_ollama import OllamaEmbeddings  # type: ignore

            model = os.environ.get("MAMA_OLLAMA_EMBED_MODEL", "nomic-embed-text")
            base_url = os.environ.get("MAMA_OLLAMA_BASE_URL", "http://127.0.0.1:11434")
            return OllamaEmbeddings(model=model, base_url=base_url)
        except Exception as exc:  # pragma: no cover
            logging.warning("Ollama embeddings unavailable, fallback to simple: %s", exc)
            return SimpleEmbeddings()

    logging.warning("Unknown embeddings backend '%s', fallback to simple", selected)
    return SimpleEmbeddings()
