"""Lesson 6: combine keyword and vector results with Reciprocal Rank Fusion (RRF)."""
from __future__ import annotations

from .documents import Chunk


def reciprocal_rank_fusion(*result_lists: list[tuple[Chunk, float]], k: int = 60,
                           top: int = 5) -> list[tuple[Chunk, float]]:
    """score(chunk) = sum over lists of 1 / (k + rank). Only ranks matter, not raw scores,
    which is why RRF can merge BM25 scores and cosine similarities that live on different scales."""
    scores: dict[str, float] = {}
    by_id: dict[str, Chunk] = {}
    for results in result_lists:
        for rank, (chunk, _) in enumerate(results, start=1):
            scores[chunk.id] = scores.get(chunk.id, 0.0) + 1.0 / (k + rank)
            by_id[chunk.id] = chunk
    ranked = sorted(scores.items(), key=lambda x: (-x[1], x[0]))
    return [(by_id[cid], s) for cid, s in ranked[:top]]
