"""Lesson 6: re-ranking a short candidate list with a more careful (slower) scorer.

Production systems use a cross-encoder or an LLM to score (query, chunk) pairs.
This stand-in rewards chunks that contain many of the query's terms, especially
close together, which is enough to demonstrate the retrieve-then-rerank pattern.
"""
from __future__ import annotations

from .documents import Chunk
from .text import terms


def overlap_rerank(query: str, candidates: list[tuple[Chunk, float]], top: int = 3) -> list[tuple[Chunk, float]]:
    q = set(terms(query))
    if not q:
        return candidates[:top]
    rescored = []
    best_prior = max((s for _, s in candidates), default=0.0) or 1.0
    for chunk, prior in candidates:
        ts = terms(chunk.text)
        coverage = len(q & set(ts)) / len(q)
        positions = [i for i, t in enumerate(ts) if t in q]
        span = (positions[-1] - positions[0] + 1) if len(positions) > 1 else len(ts) or 1
        proximity = len(positions) / span if positions else 0.0
        # Blend with the first-stage score so the reranker refines rather than overrides it.
        rescored.append((chunk, 0.5 * coverage + 0.1 * proximity + 0.4 * prior / best_prior))
    rescored.sort(key=lambda x: (-x[1], x[0].id))
    return rescored[:top]
