# RRF（Reciprocal Rank Fusion）融合算法
# 把向量排名和关键词排名合并成一个综合得分
def rrf_score(rank: int, k: int = 60) -> float:
    return 1 / (k + rank)

def merge_results(
    vec_results: list[str],    # 向量检索排序结果
    bm25_results: list[str],  # 关键词检索排序结果
) -> list[str]:
    scores: dict[str, float] = {}
    
    # 累加向量检索结果的 RRF 分数
    for rank, doc in enumerate(vec_results):
        scores[doc] = scores.get(doc, 0) + rrf_score(rank)
    
    # 累加 BM25 关键词检索结果的 RRF 分数
    for rank, doc in enumerate(bm25_results):
        scores[doc] = scores.get(doc, 0) + rrf_score(rank)
    
    # 按综合分数从高到低排序
    return sorted(scores, key=lambda d: scores[d], reverse=True)