from typing import Any, cast

from home_agent.contracts.types import EmbeddingVector


class SentenceTransformerEmbeddingProvider:
    def __init__(self, model_name: str) -> None:
        self._model_name: str = model_name
        self._model: object | None = None

    @property
    def provider_name(self) -> str:
        return "local_sentence_transformers"

    @property
    def model_name(self) -> str:
        return self._model_name

    def embed_texts(self, texts: list[str]) -> list[EmbeddingVector]:
        model = self._get_model()
        encoded = cast("Any", model).encode(texts, normalize_embeddings=True)
        values = encoded.tolist() if hasattr(encoded, "tolist") else encoded
        vectors = [[float(value) for value in row] for row in values]
        if len(vectors) != len(texts):
            msg = "embedding count mismatch"
            raise RuntimeError(msg)
        return vectors

    def _get_model(self) -> object:
        if self._model is None:
            self._model = _load_sentence_transformer(self._model_name)
        return self._model


def _load_sentence_transformer(model_name: str) -> object:
    try:
        from sentence_transformers import SentenceTransformer
    except ModuleNotFoundError as exc:
        msg = "sentence-transformers is not installed; install it to use local embeddings"
        raise RuntimeError(msg) from exc
    return SentenceTransformer(model_name)
