"""The third set of later figures, declared in after-review-r2.json before any of them was computed. Writes
results/after_review2.json from the stored aggregate CSVs, through tools/summarize.py's own functions (same arithmetic,
same bootstrap and seed). results/summary.json and results/after_review.json are read and not changed.

Usage: python3 -I -B tools/after_review2.py
"""
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
sys.path.insert(0, str(HERE))
import summarize as M  # noqa: E402

RES = ROOT / "results"
SETS = (("2026", "S"), ("2022", "S"), ("2026", "H"))
LOW, HIGH = 5.0, 15.0
TESTED = (5, 7.5, 9.5, 10, 12.5, 15)
FEW = 5  # an interval whose close or safe group holds fewer races than this is shown and not read


def r3(v):
    return None if v is None else round(v, 3)


def classified(cycle, office):
    return [k for k in M.races_of(cycle, office) if M.race[k]["prior_margin"] != ""]


def margin(k):
    return float(M.race[k]["prior_margin"])


def splits(cycle, office):
    """Every distinct split a line from LOW to HIGH gives, close below the line and safe at or above it.

    The split at LOW holds for lines from LOW up to the first prior margin at or above LOW (that margin included). Each
    later split begins just above a distinct prior margin m with LOW <= m < HIGH and holds up to the next margin, or
    HIGH, included."""
    keys = classified(cycle, office)
    cuts = sorted({margin(k) for k in keys if LOW <= margin(k) < HIGH})
    out = []
    bounds = [(LOW, True)] + [(m, False) for m in cuts]
    for i, (lo, lo_incl) in enumerate(bounds):
        hi = cuts[i] if i < len(cuts) else HIGH
        if lo_incl:
            close = [k for k in keys if margin(k) < lo]
        else:
            close = [k for k in keys if margin(k) <= lo]
        safe = [k for k in keys if k not in close]
        out.append((lo, lo_incl, hi, close, safe))
    return out


def line_in(line, lo, lo_incl, hi):
    return (lo <= line if lo_incl else lo < line) and line <= hi


def every_split():
    out = {}
    for c, o in SETS:
        rows = []
        for lo, lo_incl, hi, close, safe in splits(c, o):
            a = M.concentration(c, o, "t20", close, safe)
            seat, money, (ilo, ihi) = a["share_of_races_pct"], a["share_of_money_pct"], a["interval_pct"]
            row = {"line_low": lo, "line_low_included": lo_incl, "line_high": hi,
                   "close_races": a["close_races"], "safe_races": a["safe_races"],
                   "share_of_races_pct": seat, "share_of_money_pct": money, "interval_pct": [ilo, ihi],
                   "ratio": r3(money / seat), "interval_low_above_share_of_races": ilo > seat,
                   "too_few_races_to_read": min(a["close_races"], a["safe_races"]) < FEW,
                   "close_dollars": a["close_dollars"], "safe_dollars": a["safe_dollars"]}
            if o == "S":
                row["close_states"] = sorted(k[2] for k in close)
            rows.append(row)
        # the splits at the six tested lines must be the stored sweep's rows, figure for figure
        stored = json.loads((RES / "after_review.json").read_text(encoding="utf-8"))["sweep_t20"]
        for t in TESTED:
            got = next(r for r in rows if line_in(t, r["line_low"], r["line_low_included"], r["line_high"]))
            want = stored[f"{c}-{o}-{t:g}"]
            assert (got["close_races"], got["share_of_money_pct"], got["interval_pct"]) == (
                want["close_races"], want["share_of_money_pct"], want["interval_pct"]), (c, o, t)
        smallest = min(r["ratio"] for r in rows)
        not_above = [r for r in rows if not r["interval_low_above_share_of_races"]]
        readable = [r for r in rows if not r["too_few_races_to_read"]]
        out[f"{c}-{o}"] = {
            "splits": rows,
            "smallest_ratio": smallest,
            "smallest_ratio_splits": [[r["line_low"], r["line_low_included"], r["line_high"]] for r in rows if r["ratio"] == smallest],
            "smallest_ratio_readable": min(r["ratio"] for r in readable) if readable else None,
            "splits_interval_low_not_above_share_of_races": [[r["line_low"], r["line_low_included"], r["line_high"]] for r in not_above],
            "highest_line_interval_low_not_above_share_of_races": max((r["line_high"] for r in not_above), default=None),
            "splits_too_few_races": [[r["line_low"], r["line_low_included"], r["line_high"]] for r in rows if r["too_few_races_to_read"]],
        }
    return out


def year_difference_reading():
    """At each computed line: the share in each year, the stored 2026 minus 2022 difference and interval, the smallest
    group behind it, and whether it can be read."""
    A = json.loads((RES / "after_review.json").read_text(encoding="utf-8"))
    sw, yd = A["sweep_t20"], A["year_differences_t20"]["close_share_senate"]
    out = {}
    for t in TESTED:
        a, b = sw[f"2026-S-{t:g}"], sw[f"2022-S-{t:g}"]
        d = yd[f"{t:g}"]
        smallest = min(a["close_races"], a["safe_races"], b["close_races"], b["safe_races"])
        out[f"{t:g}"] = {"share_2026_pct": a["share_of_money_pct"], "share_2022_pct": b["share_of_money_pct"],
                         "diff_points": d["diff_points"], "interval": d["interval"], "smallest_group": smallest,
                         "too_few_races_to_read": smallest < FEW,
                         "interval_excludes_zero": d["interval"][0] > 0 or d["interval"][1] < 0,
                         "close_states_2026": a["close_states"], "close_states_2022": b["close_states"]}
    return out


def main(out_dir=RES):
    out = {"note": "Third set of later figures; see after-review-r2.json. Shares and points in percent, three decimals; "
                   "intervals are the protocol's percentile bootstrap, races resampled within close and within safe, 2000 "
                   "replicates, seed 20261103. A split holds for lines above line_low (from line_low when line_low_included) "
                   "up to line_high, included.",
           "every_split_t20": every_split(), "year_difference_reading_senate_t20": year_difference_reading(),
           "too_few_races_below": FEW}
    (Path(out_dir) / "after_review2.json").write_text(json.dumps(out, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print("wrote after_review2.json")


if __name__ == "__main__":
    main()
