"""
Practice: have you found every failure? Lab 05's discovery math (evalkit/discovery.py and
02_unseen_modes.py): the discovery curve, how many types were seen once or twice, Chao1's
estimate of the total, Good-Turing coverage, the "k failures with nothing new" stopping rule,
and the share of failures and of cost held by the types you haven't seen.

Fill in the TODOs, then run the tests:
    pytest test_saturation_practice.py        (locally)
or press "Run tests" on the chapter page.

Input everywhere is a review in order: one label per reviewed case, the failure type
(a string such as "N01") or None for a case that passed.
"""
import math
from collections import Counter

Z_95 = 1.959964


def labels_from_failures(text, n):
    """Given: rebuild a review of n cases from "position:type" pairs (1-based positions of the
    failures). Every other case passed (None)."""
    labels = [None] * n
    for pair in text.split():
        pos, mode = pair.split(":")
        if int(pos) <= n:
            labels[int(pos) - 1] = mode
    return labels


def discovery_curve(labels):
    """Distinct failure types seen after each reviewed case: a list as long as labels."""
    seen, curve = set(), []
    for label in labels:
        if label is not None:
            seen.add(label)
        curve.append(len(seen))
    return curve


def frequencies(labels):
    """{k: number of types seen exactly k times}. f1 = frequencies[1] (seen once),
    f2 = frequencies[2] (seen twice). Passes (None) don't count."""
    counts = Counter(label for label in labels if label is not None)
    return dict(Counter(counts.values()))


def chao1(labels):
    """Chao1's estimate of the total number of types, seen and unseen:
    seen + f1 * (f1 - 1) / (2 * (f2 + 1)).
    Return {"observed": seen, "f1": f1, "f2": f2, "estimate": estimate}."""
    freq = frequencies(labels)
    seen = sum(freq.values())
    f1, f2 = freq.get(1, 0), freq.get(2, 0)
    return {"observed": seen, "f1": f1, "f2": f2, "estimate": seen + f1 * (f1 - 1) / (2 * (f2 + 1))}


def chao1_interval(c, z=Z_95):
    """Given: Chao's log-normal 95% range for a chao1() result. It never goes below the types seen."""
    s_obs, f1, f2 = c["observed"], c["f1"], c["f2"]
    t = c["estimate"] - s_obs
    var = (f1 * (f1 - 1) / (2 * (f2 + 1))
           + f1 * (2 * f1 - 1) ** 2 / (4 * (f2 + 1) ** 2)
           + f1 * f1 * f2 * (f1 - 1) ** 2 / (4 * (f2 + 1) ** 4))
    if t <= 0 or var <= 0:
        return float(s_obs), float(s_obs)
    k = math.exp(z * math.sqrt(math.log(1 + var / (t * t))))
    return s_obs + t / k, s_obs + t * k


def good_turing_coverage(labels):
    """Good-Turing: the share of all failures that belong to types already seen, about
    1 - f1 / failures. Return float("nan") if there are no failures."""
    failures = sum(label is not None for label in labels)
    if failures == 0:
        return float("nan")
    return 1 - frequencies(labels).get(1, 0) / failures


def saturation_point(labels, window=20):
    """The stopping rule: the number of cases reviewed when `window` FAILURES in a row first
    brought no new type. Passes don't break or extend the streak. None if it never happens."""
    seen, streak = set(), 0
    for i, label in enumerate(labels, start=1):
        if label is None:
            continue
        if label in seen:
            streak += 1
            if streak >= window:
                return i
        else:
            seen.add(label)
            streak = 0
    return None


def unseen_shares(seen, share, cost):
    """Only a simulation can do this: given the types seen, each type's true share of requests
    (share: {type: rate}) and its cost per failure (cost: {type: cost}), return
    (share of all failures in unseen types, share of all failure cost in unseen types)."""
    total_f = sum(share.values())
    total_c = sum(share[m] * cost[m] for m in share)
    unseen = [m for m in share if m not in seen]
    return (sum(share[m] for m in unseen) / total_f,
            sum(share[m] * cost[m] for m in unseen) / total_c)
