"""
Solution: search ranking and search freshness. Lab 11's logic for scripts 01_search.py and
05_freshness.py (inverted_index.py, search_metrics.py and the CDC worker in service/cdc.py):
an inverted index with BM25, Postgres-style every-word matching, nDCG, how long a new row
waits for the next refresh, and a worker that never loses a change.
"""
import math
import re
from collections import Counter

TOKEN = re.compile(r"[^\W_]+", re.UNICODE)


def tokenize(text):
    """Lowercase, then split on anything that isn't a letter or a digit."""
    return TOKEN.findall(text.lower())


def build_index(docs):
    """docs: {doc id: text}. Returns (postings, lengths): postings is {word: {doc id: times
    the word appears in that doc}}, lengths is {doc id: number of words}."""
    postings, lengths = {}, {}
    for doc_id, text in docs.items():
        words = tokenize(text)
        lengths[doc_id] = len(words)
        for word, tf in Counter(words).items():
            postings.setdefault(word, {})[doc_id] = tf
    return postings, lengths


def idf(n_docs, df):
    """BM25's weight for a word found in df of n_docs documents: ln(1 + (N - df + 0.5) / (df + 0.5))."""
    return math.log(1 + (n_docs - df + 0.5) / (df + 0.5))


def bm25(weight, tf, length, avg_len, k1=1.2, b=0.75):
    """What one document earns from one word: weight * tf / (tf + k1 * (1 - b + b * length / avg_len))."""
    return weight * tf / (tf + k1 * (1 - b + b * length / avg_len))


def search(postings, lengths, query, k=10):
    """Top k (doc id, score), best first, ties broken by doc id. A document's score is the sum of
    bm25() over the query's words (a word repeated in the query counts each time). Only documents
    containing at least one query word are returned."""
    n = len(lengths)
    avg = sum(lengths.values()) / n
    scores = {}
    for word in tokenize(query):
        post = postings.get(word)
        if not post:
            continue
        w = idf(n, len(post))
        for doc, tf in post.items():
            scores[doc] = scores.get(doc, 0.0) + bm25(w, tf, lengths[doc], avg)
    return sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))[:k]


def match_all(postings, query, stopwords=()):
    """Postgres's plainto_tsquery, simplified: the sorted doc ids that contain every word of the
    query, after dropping stopwords. No words left: no results."""
    words = [w for w in tokenize(query) if w not in stopwords]
    if not words:
        return []
    docs = None
    for w in set(words):
        have = set(postings.get(w, {}))
        docs = have if docs is None else docs & have
    return sorted(docs)


def ndcg_at_k(ranked, relevant, k=10):
    """relevant: {doc id: grade > 0}. A relevant doc at rank r (1-based) adds grade / log2(r + 1);
    divide by the same sum for the best possible order. Raise ValueError if relevant is empty."""
    if not relevant:
        raise ValueError("no relevant documents for this query")

    def dcg(gains):
        return sum(g / math.log2(i + 2) for i, g in enumerate(gains))

    gains = [relevant.get(d, 0) for d in ranked[:k]]
    ideal = sorted(relevant.values(), reverse=True)[:k]
    return dcg(gains) / dcg(ideal)


def mean_quality(results, qrels, k=10):
    """Mean nDCG@k over every query in qrels. results: {query id: ranked doc ids}; a query with
    an empty (or missing) result scores 0, as in the lab."""
    total = 0.0
    for qid, rel in qrels.items():
        ranked = results.get(qid) or []
        total += ndcg_at_k(ranked, rel, k) if ranked else 0.0
    return total / len(qrels)


def found_after_ms(written_ms, cdc_ms, refresh_ms):
    """The refresh model: a row written at written_ms reaches the index cdc_ms later, and becomes
    searchable at the first refresh strictly after that (refreshes at 0, R, 2R, ...). Return how
    long after the write it is found."""
    arrives = written_ms + cdc_ms
    next_refresh = (math.floor(arrives / refresh_ms) + 1) * refresh_ms
    return next_refresh - written_ms


def sync_once(log, bookmark, index, crash_before_advance=False):
    """One pass of the CDC worker. log: list of (position, doc id, text), positions increasing;
    text None means the row was deleted. Take every change after `bookmark` (peek, without
    removing anything), apply them to `index` (a dict standing in for OpenSearch: write by id, or
    delete), and return the new bookmark: the last position applied. If crash_before_advance,
    the changes are applied but the bookmark is not moved: return the old one."""
    changes = [c for c in log if c[0] > bookmark]
    for _, doc_id, text in changes:
        if text is None:
            index.pop(doc_id, None)
        else:
            index[doc_id] = text
    if crash_before_advance or not changes:
        return bookmark
    return changes[-1][0]
