from __future__ import annotations

from mikoshi.retrieval.lexical import tokenize
from mikoshi.utils.types import Chunk


def rerank(
    query: str,
    candidates: list[tuple[int, float]],
    chunks: list[Chunk],
    boost: float = 0.1,
) -> list[tuple[int, float]]:
    if not candidates:
        return []

    query_tokens = set(tokenize(query))
    if not query_tokens:
        return candidates

    reranked: list[tuple[int, float]] = []
    for idx, score in candidates:
        chunk_tokens = set(tokenize(chunks[idx].text))
        overlap = len(query_tokens & chunk_tokens)
        adjusted = score + boost * (overlap / max(1, len(query_tokens)))
        reranked.append((idx, adjusted))

    return sorted(reranked, key=lambda item: item[1], reverse=True)
