"""Third version (CHANGES-r3.md): totals against the source's own units, bounds on the quick checks, the test at one
confidence level, and the share of its catch the rebuild needs to pay for itself.

Reads the frozen first-version results, results/change2-r2.json, assumptions.json and, for part A, the raw tables in
the work database built by `tools/run_study.py prepare` (opened read-only). Writes results/change3-r3.json.
Usage: python3 -B tools/change3.py <work dir>
"""
import json
import math
import sys
from pathlib import Path

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

ROOT = lib.ROOT
RES = ROOT / "results"
ALPHA = 0.05   # one-sided, throughout


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


# ---------- part A ----------
def source_side_diffs(con, patch):
    """Source-side totals with the faulted document's units minus the same with the correct document's units."""
    right = checks.source_totals(con, lib.RULES)
    wrong = checks.source_totals(con, lib.patch_rules(lib.RULES, patch))
    names = ["count", "principal", "guaranteed", "chargeoff"]
    out = {}
    for src in ("7A", "504", "HMDA"):
        for i, n in enumerate(names):
            d = wrong[src][i] - right[src][i]
            if (i == 0 and d != 0) or (i > 0 and abs(d) > checks.TOL):
                out[f"{src}.{n}"] = round(d, 2)
    return out


def part_a(con, faults, patches):
    rows = []
    for f in faults:
        first = f["fired"]["totals"]
        diffs = source_side_diffs(con, patches[f["id"]]) if f["layer"] == "rule" else {}
        rows.append({"id": f["id"], "layer": f["layer"], "totals_first": first, "source_units_diffs": diffs,
                     "totals_source_units": first or bool(diffs)})
    return {"faults": len(rows), "totals_first": sum(r["totals_first"] for r in rows),
            "totals_source_units": sum(r["totals_source_units"] for r in rows),
            "newly_caught": [r["id"] for r in rows if r["totals_source_units"] and not r["totals_first"]], "rows": rows}


# ---------- part B ----------
def part_b(faults):
    fl = [f["fired"] for f in faults]
    quick = [f["id"] for f, x in zip(faults, fl) if x["cheap_set"]]
    rules_alone = [f["id"] for f, x in zip(faults, fl) if x["target_rules"] and not x["totals"] and not x["code_census"]]
    without_rules = [f["id"] for f, x in zip(faults, fl) if x["totals"] or x["code_census"]]
    assert len(quick) == len(rules_alone) + len(without_rules)
    return {"faults": len(faults), "quick": len(quick), "rules_alone": rules_alone,
            "quick_without_rules": len(without_rules)}


# ---------- part C ----------
def binom_cdf(k, n, p):
    return sum(math.comb(n, i) * p ** i * (1 - p) ** (n - i) for i in range(k + 1))


def upper_one_sided(k, n, alpha=ALPHA):
    """Exact one-sided upper bound: the p at which P(X <= k) = alpha."""
    if k >= n:
        return 1.0
    lo, hi = k / n, 1.0
    for _ in range(200):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if binom_cdf(k, n, mid) > alpha else (lo, mid)
    return (lo + hi) / 2


def power_n(p_true, line=0.10, power=0.80, n_max=3000):
    """Smallest n at which the one-sided upper bound falls under `line` with at least `power` chance at p_true."""
    k = -1   # largest miss count still giving a bound under the line; it never falls as n grows
    for n in range(1, n_max + 1):
        while k + 1 <= n and upper_one_sided(k + 1, n) < line:
            k += 1
        if k >= 0:
            # binomial tail by a stable sum in log space
            lp, lq = math.log(p_true), math.log1p(-p_true)
            cdf = 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 + 1))
            if cdf >= power:
                return {"n": n, "max_misses": k, "power": cdf}
    raise RuntimeError("no n found")


def main(work):
    main_r, fresh_r, summ = load("main-r1.json"), load("fresh-r1.json"), load("summary-r1.json")
    a = json.loads((ROOT / "assumptions.json").read_text(encoding="utf-8"))
    patches = {f["id"]: f.get("patch") for f in lib.PROTOCOL["main_faults"]}
    patches.update({f["id"]: f.get("patch") for f in fresh_r["faults"]})
    con = lib.connect(Path(work) / "study.duckdb", read_only=True)
    out = {"declaration": "CHANGES-r3.md",
           "totals_source_units": {"main": part_a(con, main_r["faults"], patches),
                                   "fresh": part_a(con, fresh_r["faults"], patches)},
           "quick_check_bounds": {"main": part_b(main_r["faults"]), "fresh": part_b(fresh_r["faults"])}}
    con.close()

    rev = summ["reversal"]
    k, n = len(rev["fresh_chargeoff_missed_by_cheap_set"]), len(rev["fresh_chargeoff_faults"])
    p_obs = k / n
    zero_n = next(m for m in range(1, 1000) if upper_one_sided(0, m) < 0.10)
    out["test"] = {"confidence": "one-sided 95%", "chargeoff_miss": {"missed": k, "of": n, "upper": upper_one_sided(k, n)},
                   "zero_miss_n": zero_n, "zero_miss_upper": upper_one_sided(0, zero_n),
                   "zero_miss_pass_chance_at_observed": (1 - p_obs) ** zero_n,
                   "zero_miss_pass_chance_at_line": 0.9 ** zero_n,
                   "sized_for_80pct": power_n(p_obs)}

    fresh = summ["combinations"]["cheap_set_plus_record_compare"]["fresh"]["caught"]
    quick = summ["checks"]["cheap_set"]["fresh"]["caught"]
    nf, day = a["faults_per_conversion"]["base"], a["analyst_day_usd"]["base"]
    cost = a["cost_per_escaped_fault_usd"]["base"]
    removed = nf * (fresh - quick) / summ["checks"]["cheap_set"]["fresh"]["of"]
    reb = a["effort_days"]["rebuild"]
    out["rebuild_share_needed"] = {"cost_per_escaped_fault_usd": cost, "faults_removed_per_conversion": removed,
                                   "by_days": {f"{reb[x]}": reb[x] * day / (removed * cost) for x in ("low", "base", "high")}}
    (RES / "change3-r3.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    for s in ("main", "fresh"):
        t, b = out["totals_source_units"][s], out["quick_check_bounds"][s]
        print(s, {x: t[x] for x in ("faults", "totals_first", "totals_source_units", "newly_caught")},
              {"quick": b["quick"], "rules_alone": len(b["rules_alone"]), "quick_without_rules": b["quick_without_rules"]})
    print(json.dumps(out["test"]))
    print(json.dumps(out["rebuild_share_needed"]))


if __name__ == "__main__":
    main(sys.argv[1])
