import hashlib
import math


class HashEmbeddingProvider:
    def __init__(
        self,
        model_name: str = "hash-64",
        dimensions: int = 64,
        provider_name: str = "local",
    ) -> None:
        self._model_name: str = model_name
        self._dimensions: int = dimensions
        self._provider_name: str = provider_name

    @property
    def provider_name(self) -> str:
        return self._provider_name

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

    def embed_texts(self, texts: list[str]) -> list[list[float]]:
        return [_embed_text(text, self._dimensions) for text in texts]


def _embed_text(text: str, dimensions: int) -> list[float]:
    vector = [0.0] * dimensions
    tokens = [token for token in text.lower().split() if token]
    if not tokens:
        return vector

    for token in tokens:
        digest = hashlib.sha256(token.encode("utf-8")).digest()
        bucket = int.from_bytes(digest[:4], "big") % dimensions
        sign = 1.0 if digest[4] % 2 == 0 else -1.0
        magnitude = 1.0 + (digest[5] / 255.0)
        vector[bucket] += sign * magnitude

    norm = math.sqrt(sum(value * value for value in vector))
    if norm == 0.0:
        return vector
    return [value / norm for value in vector]
