"""
Practice: the checks behind Lab 18's self-repairing search index. None of them needs the right
answers. You'll compare the index's fingerprints with what's published (freshness), decide whether
a rise in "I don't know" is an alarm or chance, check a rebuild before it's swapped in, and pick
what the system should do about each of the five planted problems.

Fill in the TODOs, then run the tests:
    pytest test_repair_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
from math import comb


def freshness(index_manifest: dict, published: dict) -> dict:
    """Both are {article name: fingerprint of its text}. Return the sorted names that are
    {"new": published but not in the index, "changed": in both with different fingerprints,
     "removed": in the index but no longer published}."""
    # TODO
    raise NotImplementedError


def binom_sf(k: int, n: int, p: float) -> float:
    """The chance of k or more out of n, if each one happens with probability p:
    the sum over i = k..n of comb(n, i) * p**i * (1 - p)**(n - i). (k <= 0 → 1.0)"""
    # TODO
    raise NotImplementedError


def alarm(k: int, n: int, normal: float, alpha: float = 0.01) -> bool:
    """k of the last n answers said "I don't know"; `normal` is the usual share. Alarm only with
    at least 10 answers, a share above normal, and binom_sf(k, n, normal) below alpha."""
    # TODO
    raise NotImplementedError


def accept_rebuild(new_recall: float, normal_recall: float, tolerance: float = 0.02) -> bool:
    """Check a rebuilt index before it serves anyone: keep it only if its probe recall is no more
    than `tolerance` below normal. Otherwise keep the old index and call a person."""
    # TODO
    raise NotImplementedError


def diagnose(stale: bool, probe_recall: float, normal_recall: float, rebuild_recall: float,
             symptoms: bool, new_topic: bool) -> str:
    """What the diagnose-first policy does, in this order:
    - the index is stale                                → "rebuild"
    - probe recall more than 5 points below normal:
        a rebuild would score higher (rebuild_recall)   → "rebuild"
        otherwise (a rebuild can't fix it)              → "call on-call"
    - symptoms alarm, or a new topic of refused questions → "call docs"
    - otherwise                                         → "nothing"
    """
    # TODO
    raise NotImplementedError
