"""Lesson 4: keyword search with BM25 (Okapi BM25)."""
from __future__ import annotations

import math
from collections import Counter

from .documents import Chunk
from .text import terms


class BM25Index:
    """score(q, d) = sum over query terms t of
         idf(t) * tf(t,d) * (k1 + 1) / (tf(t,d) + k1 * (1 - b + b * len(d) / avg_len))
       idf(t) = ln(1 + (N - df(t) + 0.5) / (df(t) + 0.5))
    """

    def __init__(self, chunks: list[Chunk], k1: float = 1.5, b: float = 0.75):
        self.chunks, self.k1, self.b = chunks, k1, b
        self.tfs = [Counter(terms(c.text)) for c in chunks]
        self.lengths = [sum(tf.values()) for tf in self.tfs]
        self.avg_len = (sum(self.lengths) / len(self.lengths)) if chunks else 0.0
        df: Counter = Counter()
        for tf in self.tfs:
            df.update(tf.keys())
        n = len(chunks)
        self.idf = {t: math.log(1 + (n - d + 0.5) / (d + 0.5)) for t, d in df.items()}

    def score(self, query: str, i: int) -> float:
        tf, length = self.tfs[i], self.lengths[i]
        s = 0.0
        for t in set(terms(query)):
            f = tf.get(t, 0)
            if f:
                norm = self.k1 * (1 - self.b + self.b * length / (self.avg_len or 1))
                s += self.idf[t] * f * (self.k1 + 1) / (f + norm)
        return s

    def search(self, query: str, k: int = 5) -> list[tuple[Chunk, float]]:
        scored = [(self.chunks[i], self.score(query, i)) for i in range(len(self.chunks))]
        scored = [x for x in scored if x[1] > 0]
        scored.sort(key=lambda x: (-x[1], x[0].id))
        return scored[:k]
