"""Lesson 5: embeddings turn text into vectors where similar meaning means nearby vectors.

HashingEmbedder is an offline stand-in so every lesson runs without downloads or
API keys. It only captures word overlap (no real meaning), which is exactly what
lets you SEE the difference when you switch to a real embedding model via
OpenAICompatibleEmbedder (Ollama, LM Studio, vLLM, or a hosted API).
"""
from __future__ import annotations

import hashlib
import json
import math
import os
import urllib.request

from .text import terms


def normalize(v: list[float]) -> list[float]:
    n = math.sqrt(sum(x * x for x in v))
    return [x / n for x in v] if n else v


class HashingEmbedder:
    """Feature hashing of word unigrams and bigrams into `dim` buckets, L2-normalized."""

    def __init__(self, dim: int = 512):
        self.dim = dim

    def _bucket(self, feature: str) -> tuple[int, float]:
        h = int.from_bytes(hashlib.blake2b(feature.encode(), digest_size=8).digest(), "big")
        return h % self.dim, (1.0 if (h >> 63) & 1 else -1.0)

    def embed(self, texts: list[str]) -> list[list[float]]:
        out = []
        for text in texts:
            v = [0.0] * self.dim
            ts = terms(text)
            for feat in ts + [f"{a}_{b}" for a, b in zip(ts, ts[1:])]:
                i, sign = self._bucket(feat)
                v[i] += sign
            out.append(normalize(v))
        return out


class OpenAICompatibleEmbedder:
    """Calls any server that implements the OpenAI-style POST /v1/embeddings endpoint.

    Examples:
      Ollama (local):  OpenAICompatibleEmbedder("http://localhost:11434/v1", "nomic-embed-text")
      Hosted API:      OpenAICompatibleEmbedder("https://api.openai.com/v1", "<embedding model>", api_key=...)
    """

    def __init__(self, base_url: str, model: str, api_key: str | None = None, timeout: float = 60):
        self.base_url, self.model, self.timeout = base_url.rstrip("/"), model, timeout
        self.api_key = api_key if api_key is not None else os.environ.get("OPENAI_API_KEY", "")

    def embed(self, texts: list[str], batch_size: int = 64) -> list[list[float]]:
        vectors: list[list[float]] = []
        for start in range(0, len(texts), batch_size):
            body = json.dumps({"model": self.model, "input": texts[start:start + batch_size]}).encode()
            req = urllib.request.Request(f"{self.base_url}/embeddings", data=body, method="POST",
                                         headers={"Content-Type": "application/json",
                                                  **({"Authorization": f"Bearer {self.api_key}"} if self.api_key else {})})
            with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                data = json.load(resp)["data"]
            vectors += [normalize(item["embedding"]) for item in sorted(data, key=lambda d: d["index"])]
        return vectors
