"""Embedding service facade in sagellm.

This is the canonical service entrypoint replacing `sage.common.components.sage_embedding`.
"""

from __future__ import annotations

from dataclasses import dataclass

from .client import EmbeddingClient


@dataclass(slots=True)
class EmbeddingService:
    """Thin service facade for embedding generation via sagellm endpoint."""

    client: EmbeddingClient
    normalize: bool = True

    @classmethod
    def from_endpoint(
        cls,
        base_url: str = "http://127.0.0.1:8890",
        model: str = "sentence-transformers/all-MiniLM-L6-v2",
        timeout_s: float = 30.0,
        normalize: bool = True,
    ) -> EmbeddingService:
        return cls(
            client=EmbeddingClient(base_url=base_url, default_model=model, timeout_s=timeout_s),
            normalize=normalize,
        )

    def embed(self, texts: list[str], model: str | None = None) -> list[list[float]]:
        vectors = self.client.embed(texts, model=model)
        if not self.normalize:
            return vectors
        return [self._normalize(vec) for vec in vectors]

    def embed_one(self, text: str, model: str | None = None) -> list[float]:
        vectors = self.embed([text], model=model)
        return vectors[0] if vectors else []

    @staticmethod
    def _normalize(vec: list[float]) -> list[float]:
        norm = sum(x * x for x in vec) ** 0.5
        if norm <= 0:
            return vec
        return [x / norm for x in vec]
