"""
Practice: 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.

Fill in the TODOs, then run the tests:
    pytest test_search_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
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."""
    # TODO
    raise NotImplementedError


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}."""
    # TODO
    raise NotImplementedError


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))."""
    # TODO
    raise NotImplementedError


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))."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError
