"""Tests on Lab 11's logic and recorded runs (2 November 2026, Apple M4 Max, Docker Desktop with
16 vCPU): 01_search.py (our BM25 vs OpenSearch vs Postgres on SciFact's 5,183 abstracts and
1,109 claims) and 05_freshness.py (a new Postgres row until search finds it). The small index
tests are the lab's own (tests/test_inverted_index.py); the numbers are the recorded results.
Run: pytest test_search_practice.py"""
import math

from search_practice import (bm25, build_index, found_after_ms, idf, match_all, mean_quality, ndcg_at_k, search,
                             sync_once, tokenize)

DOCS = {
    "a": "The cat sat on the mat",
    "b": "The dog sat on the log",
    "c": "Cats and dogs: a short history of cats",
    "d": "Quantum chromodynamics of the strong interaction",
    "e": "the the the the the the the the the cat",
}
N_SCIFACT, AVG_LEN = 5183, 225.3278024310245


def close(a, b, tol=1e-9):
    return abs(a - b) <= tol


def test_tokenize_like_the_standard_analyzer():
    assert tokenize("Cats, dogs & COVID-19 (2020)") == ["cats", "dogs", "covid", "19", "2020"]
    assert tokenize("0-dimensional biomaterials lack inductive properties.") == [
        "0", "dimensional", "biomaterials", "lack", "inductive", "properties"]


def test_build_index():
    postings, lengths = build_index(DOCS)
    assert lengths == {"a": 6, "b": 6, "c": 8, "d": 6, "e": 10}
    assert postings["cat"] == {"a": 1, "e": 1}
    assert postings["the"]["e"] == 9
    assert "cats" in postings and postings["cats"] == {"c": 2}     # no stemming: "cats" isn't "cat"


def test_idf_rare_words_count_more():
    # SciFact, claim 0: "biomaterials" is in 1 abstract, "properties" in 211, "the" in 5,159
    assert close(idf(N_SCIFACT, 1), math.log(3456), 1e-12)
    assert round(idf(N_SCIFACT, 1), 2) == 8.15
    assert round(idf(N_SCIFACT, 211), 1) == 3.2
    assert idf(N_SCIFACT, 5159) < 0.005


def test_repeats_add_less():
    w = idf(N_SCIFACT, 1)
    earned = [round(bm25(w, tf, AVG_LEN, AVG_LEN), 1) for tf in (1, 2, 10)]
    assert earned == [3.7, 5.1, 7.3]
    assert bm25(w, 1000, AVG_LEN, AVG_LEN) < w                    # never more than the weight


def test_short_documents_count_more():
    w = idf(N_SCIFACT, 1)
    assert bm25(w, 1, AVG_LEN / 2, AVG_LEN) > bm25(w, 1, AVG_LEN, AVG_LEN) > bm25(w, 1, 2 * AVG_LEN, AVG_LEN)


def test_bm25_score_by_hand():
    postings, lengths = build_index(DOCS)
    avg = (6 + 6 + 8 + 6 + 10) / 5
    want = math.log(1 + 4.5 / 1.5) * 1 / (1 + 1.2 * (1 - 0.75 + 0.75 * 6 / avg))
    top = search(postings, lengths, "mat")
    assert top[0][0] == "a" and close(top[0][1], want, 1e-9) and len(top) == 1


def test_search_ranks_rare_terms_and_short_documents():
    postings, lengths = build_index(DOCS)
    assert search(postings, lengths, "cat sat")[0][0] == "a"      # both words, short document
    assert search(postings, lengths, "the")[0][0] == "e"          # most "the"s, despite its length
    assert search(postings, lengths, "zebra") == []
    assert [d for d, _ in search(postings, lengths, "sat")] == ["a", "b"]   # a tie, broken by id


def test_every_word_finds_nothing_for_sentences():
    postings, _ = build_index(DOCS)
    stop = {"the", "on", "a", "of", "and"}
    assert match_all(postings, "the cat sat on the mat", stop) == ["a"]
    assert match_all(postings, "the cat sat on the log", stop) == []     # no document has them all
    assert match_all(postings, "the", stop) == []                         # only stopwords: nothing
    postings_any, lengths = build_index(DOCS)
    assert [d for d, _ in search(postings_any, lengths, "the cat sat on the log")][:2] == ["b", "a"]   # any word: results


def test_ndcg():
    rel = {"a": 1, "b": 1}
    assert close(ndcg_at_k(["a", "b", "x"], rel), 1.0)
    assert ndcg_at_k(["x", "a", "b"], rel) < 1.0
    assert ndcg_at_k(["x", "y"], rel) == 0.0
    try:
        ndcg_at_k(["a"], {})
    except ValueError:
        pass
    else:
        raise AssertionError("expected ValueError")


def test_empty_answers_score_zero():
    # Postgres, every word: 85 of 1,109 claims answered, quality about 0.91 on those, 0.070 overall
    qrels = {str(i): {"rel": 1} for i in range(1109)}
    results = {str(i): ["rel"] for i in range(77)}                        # 77 perfect answers...
    results.update({str(i): ["x", "y"] for i in range(77, 85)})           # ...8 that missed
    results.update({str(i): [] for i in range(85, 1109)})                 # 1,024 empty
    q = mean_quality(results, qrels)
    assert close(q, 77 / 1109)
    assert round(q, 2) == 0.07
    assert round(mean_quality(results, {k: v for k, v in qrels.items() if int(k) < 85}), 2) == 0.91


def test_refresh_model():
    assert found_after_ms(300, 18, 1000) == 700        # reaches the index at 318, refresh at 1,000
    assert found_after_ms(990, 18, 1000) == 1010       # just missed one refresh: waits for the next
    waits = [found_after_ms(t, 18, 1000) for t in range(1000)]
    assert close(sum(waits) / len(waits), 18 + 500, 1.0)      # about half the interval, plus the worker
    assert max(waits) == 1018 and min(waits) == 19
    # Recorded: 534 ms median with a 1 s refresh, 82 ms with 100 ms
    fast = [found_after_ms(t, 23, 100) for t in range(100)]
    assert 70 <= sum(fast) / len(fast) <= 80 and max(fast) == 123


def test_worker_crash_resends_but_loses_nothing():
    log = [(1, "r1", "one"), (2, "r2", "two"), (3, "r3", "three")]
    index = {}
    mark = sync_once(log, 0, index, crash_before_advance=True)    # sent, then crashed
    assert mark == 0 and index == {"r1": "one", "r2": "two", "r3": "three"}
    mark = sync_once(log, mark, index)                            # restart: the same changes again
    assert mark == 3 and len(index) == 3                          # overwritten by id, not duplicated


def test_worker_stopped_catches_up():
    # Writes go on while the worker is stopped; the log keeps them all.
    log = [(i, f"fresh-{i}", f"probe {i}") for i in range(1, 401)]
    index = {}
    mark = sync_once(log[:100], 0, index)
    assert mark == 100
    mark = sync_once(log, mark, index)                            # back after the outage: one big batch
    assert mark == 400 and len(index) == 400
    assert sync_once(log + [(401, "fresh-7", None)], mark, index) == 401 and "fresh-7" not in index
