"""Fourth version (CHANGES-r4.md): the reversal line at the low end of the quick checks, code faults past them at both
ends, the draws the test needs, and totals by fault kind.

Reads only stored results (results/*-r1.json, results/change3-r3.json). Writes results/change4-r4.json.
Usage: python3 -B tools/change4.py
"""
import json
import math
import sys
from collections import defaultdict
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import lib  # noqa: E402

RES = lib.ROOT / "results"
SUMMED = {"principal_usd", "guaranteed_usd", "chargeoff_usd"}


def load(name):
    return json.loads((RES / name).read_text(encoding="utf-8"))


def quick_low(fired):
    """The quick checks with the target rules removed: totals and the code census only."""
    return fired["totals"] or fired["code_census"]


def touches_totals(f):
    """Read from the fault's stored effect on the converted table, not from the totals flag."""
    e = f["effect"]
    return bool(e["missing"] or e["extra_copies"] or e.get("extra_ids", 0) or SUMMED & set(e["fields"]))


def binom_sf(k, n, p):
    """P(X >= k) for X ~ Binomial(n, p), summed in log space."""
    lp, lq = math.log(p), math.log1p(-p)
    return sum(math.exp(math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1) + i * lp + (n - i) * lq)
               for i in range(k, n + 1))


def draws_needed(r, p, chance=0.95):
    n = r
    while binom_sf(r, n, p) < chance:
        n += 1
    return n


def by_kind(faults):
    rows, table = [], defaultdict(lambda: {"faults": 0, "touch": 0, "caught": 0, "caught_touch": 0, "caught_other": 0})
    for f in faults:
        touch = f["layer"] == "code" and touches_totals(f)
        caught = bool(f["fired"]["totals"])
        rows.append({"id": f["id"], "layer": f["layer"], "family": f.get("family"), "touches": touch, "totals": caught})
        for key in (f["layer"], f"{f['layer']}.{f.get('family') or 'chosen'}"):
            t = table[key]
            t["faults"] += 1
            t["touch"] += touch
            t["caught"] += caught
            t["caught_touch"] += caught and touch
            t["caught_other"] += caught and not touch
    return {"table": dict(table), "rows": rows}


def compute():
    main_r, fresh_r, summ, c3 = load("main-r1.json"), load("fresh-r1.json"), load("summary-r1.json"), load("change3-r3.json")
    fresh = {f["id"]: f for f in fresh_r["faults"]}
    rev = summ["reversal"]
    co = rev["fresh_chargeoff_faults"]
    miss_high = [i for i in co if not fresh[i]["fired"]["cheap_set"]]
    miss_low = [i for i in co if not quick_low(fresh[i]["fired"])]
    assert miss_high == rev["fresh_chargeoff_missed_by_cheap_set"]
    code = [f for f in fresh_r["faults"] if f["layer"] == "code"]
    past_high = [f["id"] for f in code if not f["fired"]["cheap_set"]]
    past_low = [f["id"] for f in code if not quick_low(f["fired"])]
    assert all(fresh[i]["fired"]["record_compare"] for i in past_low)
    r = c3["test"]["sized_for_80pct"]["n"]
    p = len(co) / len(fresh_r["faults"])
    out = {"declaration": "CHANGES-r4.md",
           "reversal_low_end": {"chargeoff_faults": len(co), "missed_high": miss_high, "missed_low": miss_low,
                                "share_high": len(miss_high) / len(co), "share_low": len(miss_low) / len(co)},
           "code_past_quick": {"code_faults": len(code), "high": past_high, "low": past_low},
           "test_draws": {"chargeoff_moving_needed": r, "share_moving": p, "mean_draws": r / p,
                          "draws_for_95pct": draws_needed(r, p)},
           "totals_by_kind": {"main": by_kind(main_r["faults"]), "fresh": by_kind(fresh_r["faults"])}}
    return out


def main():
    out = compute()
    (RES / "change4-r4.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    print(json.dumps({k: out[k] for k in ("reversal_low_end", "code_past_quick", "test_draws")}))
    for s in ("main", "fresh"):
        t = out["totals_by_kind"][s]["table"]
        print(s, {k: t[k] for k in ("code", "rule") if k in t})


if __name__ == "__main__":
    main()
