"""Solution for repair_practice.py (Lab 18, script 04's checks)."""
from math import comb


def freshness(index_manifest: dict, published: dict) -> dict:
    return {"new": sorted(set(published) - set(index_manifest)),
            "changed": sorted(n for n in published if n in index_manifest and published[n] != index_manifest[n]),
            "removed": sorted(set(index_manifest) - set(published))}


def binom_sf(k: int, n: int, p: float) -> float:
    if k <= 0:
        return 1.0
    return min(1.0, sum(comb(n, i) * p ** i * (1 - p) ** (n - i) for i in range(k, n + 1)))


def alarm(k: int, n: int, normal: float, alpha: float = 0.01) -> bool:
    return n >= 10 and k / n > normal and binom_sf(k, n, normal) < alpha


def accept_rebuild(new_recall: float, normal_recall: float, tolerance: float = 0.02) -> bool:
    return new_recall >= normal_recall - tolerance


def diagnose(stale: bool, probe_recall: float, normal_recall: float, rebuild_recall: float,
             symptoms: bool, new_topic: bool) -> str:
    if stale:
        return "rebuild"
    if probe_recall < normal_recall - 0.05:
        return "rebuild" if rebuild_recall > probe_recall else "call on-call"
    if symptoms or new_topic:
        return "call docs"
    return "nothing"
