"""Retrieval: embeddings, a tiny vector store, BM25, and hybrid fusion.

Implemented from scratch and small on purpose. Once you have written cosine
similarity and reciprocal rank fusion yourself, every vector database's
documentation reads as configuration rather than magic.

The through-line of the retrieval lessons: dense and lexical search fail on
*different* queries, which is exactly why combining them works. Dense search
blurs exact identifiers, error strings, and rare proper nouns; BM25 nails them
and misses paraphrase.
"""

from __future__ import annotations

import math
import re
from collections import Counter
from dataclasses import dataclass, field
from typing import Any, Callable, Iterable, Protocol


# --------------------------------------------------------------------------
# Documents
# --------------------------------------------------------------------------


@dataclass
class Chunk:
    """A retrievable unit, with the metadata retrieval actually needs.

    `permissions` is here rather than bolted on later because access control has
    to be enforced at retrieval time by filtering. Asking a model to "not reveal"
    a chunk it can see is not access control.
    """

    id: str
    text: str
    source: str = ""
    section: str = ""
    permissions: frozenset[str] = frozenset()
    embedding: tuple[float, ...] | None = None

    def with_context(self) -> str:
        """The chunk prefixed with where it came from.

        An isolated chunk is often uninterpretable - "it must be renewed within
        30 days" means nothing without the heading. Prepending the path is the
        cheapest retrieval-quality win available.
        """
        prefix = " > ".join(p for p in (self.source, self.section) if p)
        return f"[{prefix}]\n{self.text}" if prefix else self.text


# --------------------------------------------------------------------------
# Embeddings
# --------------------------------------------------------------------------


class Embedder(Protocol):
    def embed(self, text: str) -> tuple[float, ...]: ...


_TOKEN = re.compile(r"[a-z0-9]+")


def tokenize(text: str) -> list[str]:
    return _TOKEN.findall(text.lower())


class HashingEmbedder:
    """A deterministic bag-of-words embedder with no dependencies.

    This is NOT a semantic model - it cannot tell that "cheap" and "inexpensive"
    are related, because it has learned nothing. It exists so the retrieval
    lessons run offline and so the *mechanics* (dimensionality, normalization,
    cosine, indexing, fusion) are exercised end to end. Swap in a real embedding
    model by implementing `embed`, and note the migration warning: changing
    embedding model means re-indexing the whole corpus, never a config flip.
    """

    def __init__(self, dim: int = 64) -> None:
        self.dim = dim

    def embed(self, text: str) -> tuple[float, ...]:
        vec = [0.0] * self.dim
        for token in tokenize(text):
            # Stable across processes, unlike hash() which is salted per run.
            slot = _stable_hash(token) % self.dim
            vec[slot] += 1.0
        return normalize(tuple(vec))


def _stable_hash(s: str) -> int:
    h = 2166136261
    for ch in s.encode():
        h = ((h ^ ch) * 16777619) & 0xFFFFFFFF
    return h


def dot(a: Iterable[float], b: Iterable[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


def norm(a: Iterable[float]) -> float:
    return math.sqrt(sum(x * x for x in a))


def normalize(v: tuple[float, ...]) -> tuple[float, ...]:
    n = norm(v)
    return tuple(x / n for x in v) if n else v


def cosine(a: tuple[float, ...], b: tuple[float, ...]) -> float:
    """Cosine similarity. On already-normalized vectors this is just the dot product.

    Cosine rather than Euclidean because magnitude in an embedding is mostly an
    artifact and direction carries the meaning - a one-sentence and a one-page
    document on the same topic should score alike.
    """
    da, db = norm(a), norm(b)
    if da == 0 or db == 0:
        return 0.0
    return dot(a, b) / (da * db)


# --------------------------------------------------------------------------
# Results
# --------------------------------------------------------------------------


@dataclass
class Hit:
    chunk: Chunk
    score: float
    rank: int = 0
    retriever: str = ""


# --------------------------------------------------------------------------
# Dense
# --------------------------------------------------------------------------


class VectorStore:
    """Exact nearest-neighbour search by brute force.

    Exact search is linear in corpus size, which is why real systems use
    approximate indexes (HNSW, IVF-PQ) and accept recall as a tunable SLO. At the
    scale of a lesson, brute force is both correct and instant - and it is the
    baseline you measure an approximate index against.
    """

    def __init__(self, embedder: Embedder | None = None) -> None:
        self.embedder = embedder or HashingEmbedder()
        self.chunks: list[Chunk] = []

    def add(self, *chunks: Chunk) -> "VectorStore":
        for c in chunks:
            if c.embedding is None:
                c = Chunk(
                    id=c.id,
                    text=c.text,
                    source=c.source,
                    section=c.section,
                    permissions=c.permissions,
                    embedding=self.embedder.embed(c.with_context()),
                )
            self.chunks.append(c)
        return self

    def __len__(self) -> int:
        return len(self.chunks)

    def search(
        self,
        query: str,
        k: int = 5,
        permitted: frozenset[str] | None = None,
        min_score: float = 0.0,
    ) -> list[Hit]:
        """Top-k by cosine, with permission filtering applied BEFORE ranking.

        Pre-filtering matters: post-filtering a top-k list silently destroys
        recall when the filter is selective, because the permitted documents may
        all sit below the cutoff.
        """
        qv = self.embedder.embed(query)
        candidates = [
            c for c in self.chunks if _permitted(c, permitted)
        ]
        scored = [
            Hit(chunk=c, score=cosine(qv, c.embedding or ()), retriever="dense")
            for c in candidates
        ]
        scored = [h for h in scored if h.score > min_score]
        scored.sort(key=lambda h: (-h.score, h.chunk.id))
        for i, h in enumerate(scored[:k]):
            h.rank = i + 1
        return scored[:k]


def _permitted(chunk: Chunk, permitted: frozenset[str] | None) -> bool:
    if not chunk.permissions:
        return True          # public
    if permitted is None:
        return False         # restricted and no grants supplied - deny
    return bool(chunk.permissions & permitted)


# --------------------------------------------------------------------------
# Lexical
# --------------------------------------------------------------------------


class BM25:
    """Okapi BM25 - the lexical retriever dense search cannot replace.

    Wins on exactly the queries embeddings blur: order numbers, error codes,
    SKUs, rare surnames, and any literal string the user pasted in.
    """

    def __init__(self, k1: float = 1.5, b: float = 0.75) -> None:
        self.k1 = k1
        self.b = b
        self.chunks: list[Chunk] = []
        self._tokens: list[list[str]] = []
        self._df: Counter[str] = Counter()
        self._avg_len = 0.0

    def add(self, *chunks: Chunk) -> "BM25":
        for c in chunks:
            toks = tokenize(c.with_context())
            self.chunks.append(c)
            self._tokens.append(toks)
            for t in set(toks):
                self._df[t] += 1
        self._avg_len = sum(len(t) for t in self._tokens) / max(1, len(self._tokens))
        return self

    def __len__(self) -> int:
        return len(self.chunks)

    def _idf(self, term: str) -> float:
        n = len(self.chunks)
        df = self._df.get(term, 0)
        # +1 keeps the idf positive for terms present in every document.
        return math.log(1 + (n - df + 0.5) / (df + 0.5))

    def search(
        self, query: str, k: int = 5, permitted: frozenset[str] | None = None
    ) -> list[Hit]:
        q = tokenize(query)
        hits: list[Hit] = []
        for chunk, toks in zip(self.chunks, self._tokens):
            if not _permitted(chunk, permitted):
                continue
            tf = Counter(toks)
            length = len(toks) or 1
            score = 0.0
            for term in q:
                f = tf.get(term, 0)
                if not f:
                    continue
                denom = f + self.k1 * (
                    1 - self.b + self.b * length / (self._avg_len or 1)
                )
                score += self._idf(term) * (f * (self.k1 + 1)) / denom
            if score > 0:
                hits.append(Hit(chunk=chunk, score=score, retriever="bm25"))
        hits.sort(key=lambda h: (-h.score, h.chunk.id))
        for i, h in enumerate(hits[:k]):
            h.rank = i + 1
        return hits[:k]


# --------------------------------------------------------------------------
# Fusion
# --------------------------------------------------------------------------


def reciprocal_rank_fusion(
    *result_lists: list[Hit], k: int = 5, smoothing: int = 60
) -> list[Hit]:
    """Combine ranked lists by RANK POSITION, not by raw score.

    This is the whole trick. A BM25 score and a cosine score are not on a
    comparable scale, so adding or averaging them is meaningless and whichever
    retriever happens to produce larger numbers wins. Rank position is
    comparable by construction.

    `smoothing` flattens the contribution of top positions so one retriever
    being very confident cannot dominate the fused list.
    """
    fused: dict[str, Hit] = {}
    scores: Counter[str] = Counter()

    for hits in result_lists:
        for h in hits:
            scores[h.chunk.id] += 1.0 / (smoothing + h.rank)
            fused.setdefault(
                h.chunk.id, Hit(chunk=h.chunk, score=0.0, retriever="hybrid")
            )

    out = []
    for cid, score in scores.most_common():
        hit = fused[cid]
        hit.score = score
        out.append(hit)

    out.sort(key=lambda h: (-h.score, h.chunk.id))
    for i, h in enumerate(out[:k]):
        h.rank = i + 1
    return out[:k]


class HybridRetriever:
    """Dense + BM25 + RRF behind one `search`, so the agent sees one tool."""

    def __init__(self, embedder: Embedder | None = None) -> None:
        self.dense = VectorStore(embedder)
        self.lexical = BM25()

    def add(self, *chunks: Chunk) -> "HybridRetriever":
        self.dense.add(*chunks)
        self.lexical.add(*chunks)
        return self

    def __len__(self) -> int:
        return len(self.dense)

    def search(
        self,
        query: str,
        k: int = 5,
        candidates: int = 20,
        permitted: frozenset[str] | None = None,
        rerank: Callable[[str, list[Hit]], list[Hit]] | None = None,
    ) -> list[Hit]:
        """Retrieve wide, then narrow. A cheap high-recall first stage, then
        optional expensive high-precision reranking over a shortlist only."""
        d = self.dense.search(query, k=candidates, permitted=permitted)
        l = self.lexical.search(query, k=candidates, permitted=permitted)
        fused = reciprocal_rank_fusion(d, l, k=candidates)
        if rerank:
            fused = rerank(query, fused)
        for i, h in enumerate(fused[:k]):
            h.rank = i + 1
        return fused[:k]


def keyword_overlap_reranker(query: str, hits: list[Hit]) -> list[Hit]:
    """A stand-in cross-encoder: rescore a shortlist by query-term coverage.

    A real reranker reads the query and document *jointly*, which is why it is
    accurate and why it cannot be precomputed - so it only ever runs over a few
    dozen candidates. This crude version has the same shape and needs no model.
    """
    q = set(tokenize(query))
    if not q:
        return hits
    out = []
    for h in hits:
        terms = set(tokenize(h.chunk.text))
        coverage = len(q & terms) / len(q)
        out.append(Hit(chunk=h.chunk, score=coverage, retriever="reranked"))
    out.sort(key=lambda h: (-h.score, h.chunk.id))
    for i, h in enumerate(out):
        h.rank = i + 1
    return out


# --------------------------------------------------------------------------
# Retrieval quality
# --------------------------------------------------------------------------


def recall_at_k(hits: list[Hit], relevant_ids: set[str], k: int | None = None) -> float:
    """Share of relevant chunks that appear in the top k. The retriever's own score.

    Measured separately from answer quality on purpose: a RAG system fails in two
    distinct places, and one aggregate number cannot tell you which.
    """
    if not relevant_ids:
        return 1.0
    top = {h.chunk.id for h in hits[: k or len(hits)]}
    return len(top & relevant_ids) / len(relevant_ids)


def precision_at_k(hits: list[Hit], relevant_ids: set[str], k: int | None = None) -> float:
    top = [h for h in hits[: k or len(hits)]]
    if not top:
        return 0.0
    return sum(1 for h in top if h.chunk.id in relevant_ids) / len(top)


def mrr(hits: list[Hit], relevant_ids: set[str]) -> float:
    """Mean reciprocal rank of the first relevant hit - how far down the answer sits."""
    for i, h in enumerate(hits, start=1):
        if h.chunk.id in relevant_ids:
            return 1.0 / i
    return 0.0