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


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


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


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


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


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