"""Embedding generation using embeddinggemma-300m via sentence_transformers."""

import logging
import time

from mykb.core.config import get_embedding_config

logger = logging.getLogger(__name__)


class Embedder:
    def __init__(self):
        self._model = None

    @property
    def model(self):
        """Lazy-load the embedding model on first use."""
        if self._model is None:
            from sentence_transformers import SentenceTransformer

            config = get_embedding_config()
            model_name = config['model']
            logger.info(f'Loading embedding model: {model_name}...')
            t0 = time.perf_counter()
            self._model = SentenceTransformer(model_name)
            elapsed = time.perf_counter() - t0
            logger.info(f'Model loaded ({elapsed:.2f}s)')
        return self._model

    def encode_documents(self, texts: list[str]) -> list[list[float]]:
        """Encode document texts into embedding vectors."""
        if not texts:
            return []
        t0 = time.perf_counter()
        embeddings = self.model.encode_document(texts)
        elapsed = time.perf_counter() - t0
        logger.debug(f'Encoded {len(texts)} doc(s) ({elapsed:.2f}s)')
        return [vec.tolist() for vec in embeddings]

    def encode_query(self, text: str) -> list[float]:
        """Encode a search query into an embedding vector."""
        t0 = time.perf_counter()
        embedding = self.model.encode_query(text)
        elapsed = time.perf_counter() - t0
        logger.debug(f'Encoded query ({elapsed:.2f}s)')
        return embedding.tolist()
