"""The post-review figures (declared in after-review-r1.json) that replay with no download. Writes results/after_review.json.

Usage: python3 -I -B tools/after_review.py
Reads the stored aggregate CSVs through tools/summarize.py's own functions (same arithmetic, same bootstrap and seed),
results/summary.json, results/reconciliation.json and results/after_review_raw.json. results/summary.json is not changed.
"""
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"
LINES = (5, 7.5, 9.5, 10, 12.5, 15)
SETS = (("2026", "S"), ("2022", "S"), ("2026", "H"))


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 split(cycle, office, line):
    keys = classified(cycle, office)
    return [k for k in keys if margin(k) < line], [k for k in keys if margin(k) >= line]


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


def sweep():
    out = {}
    for c, o in SETS:
        for line in LINES:
            close, safe = split(c, o, line)
            a = M.concentration(c, o, "t20", close, safe)
            row = {k: a[k] for k in ("close_races", "safe_races", "share_of_races_pct", "share_of_money_pct", "interval_pct",
                                     "close_dollars", "safe_dollars")}
            if o == "S":
                row["close_states"] = sorted(k[2] for k in close)
            out[f"{c}-{o}-{line:g}"] = row
        declared = M.concentration(c, o, "t20")
        got = out[f"{c}-{o}-10"]
        assert (got["share_of_money_pct"], got["interval_pct"], got["close_races"]) == (
            declared["share_of_money_pct"], declared["interval_pct"], declared["close_races"]), (c, o)
    return out


def protocol_sensitivity():
    out = {}
    for c, o in SETS:
        keys = classified(c, o)
        close, safe = [k for k in keys if margin(k) < 5], [k for k in keys if margin(k) >= 20]
        row = {"close_races": len(close), "safe_races": len(safe), "races_between_left_out": len(keys) - len(close) - len(safe)}
        if o == "S":
            row["close_states"] = sorted(k[2] for k in close)
        out[f"{c}-{o}"] = row
    return out


def largest_close_race():
    """The close race with the most independent money through T-20 at the declared line, and the share with it counted safe."""
    out = {}
    for c, o in SETS:
        close, safe = split(c, o, 10)
        top = max(close, key=lambda k: M.ie_tot[("t20", k)])
        cd = sum(M.ie_tot[("t20", k)] for k in close)
        sd = sum(M.ie_tot[("t20", k)] for k in safe)
        t = M.ie_tot[("t20", top)]
        out[f"{c}-{o}"] = {"state": top[2], "district": top[3], "prior_margin": margin(top), "dollars": round(t),
                           "share_of_close_dollars_pct": r3(100 * t / cd), "share_of_labelled_dollars_pct": r3(100 * t / (cd + sd)),
                           "close_share_with_it_safe_pct": r3(100 * (cd - t) / (cd + sd)),
                           "share_of_races_with_it_safe_pct": r3(100 * (len(close) - 1) / (len(close) + len(safe)))}
    return out


def year_differences():
    out = {"close_share_senate": {}, "opposing_close_senate": {}}
    share = M.share_close("t20")
    for line in LINES:
        c26, s26 = split("2026", "S", line)
        c22, s22 = split("2022", "S", line)

        def fn(a, b, x, y):
            u, v = share(a, b), share(x, y)
            return u - v if u is not None and v is not None else None
        out["close_share_senate"][f"{line:g}"] = {"diff_points": r3(fn(c26, s26, c22, s22)), "interval": M.boot(fn, c26, s26, c22, s22)}
    g26, g22 = M.races_of("2026", "S", "close"), M.races_of("2022", "S", "close")
    for pty in ("D", "R"):
        def opp(g, p=pty):
            o = sum(M.ie_party[("t20", k, p, "O")] for k in g)
            s = sum(M.ie_party[("t20", k, p, "S")] for k in g)
            return 100 * o / (o + s) if o + s else None

        def fn2(a, b):
            u, v = opp(a), opp(b)
            return u - v if u is not None and v is not None else None
        out["opposing_close_senate"][pty] = {"diff_points": r3(fn2(g26, g22)), "interval": M.boot(fn2, g26, g22)}
    return out


READINGS = {"as_coded": ("digital", "digital_channel", "digital_stream", "digital_mediaword"),
            "channel_counted_as_media": ("digital", "digital_mediaword"),
            "declared_literal": ("digital",)}


def digital(raw):
    per = raw["digital_coding_senate_t20_per_race"]
    out = {}
    for label in ("close", "safe"):
        for pty in ("D", "R"):
            for name, tags in READINGS.items():
                def ds(g, p=pty, t=tags):
                    d = a = 0.0
                    for k in g:
                        row = per.get(k[0], {}).get(k[2], {}).get(p, {})
                        d += sum(row.get(x, 0.0) for x in t)
                        a += sum(row.get(x, 0.0) for x in ("media", "mail") + READINGS["as_coded"])
                    return 100 * d / a if a else None

                def fn(x, y):
                    u, v = ds(x), ds(y)
                    return u - v if u is not None and v is not None else None
                x, y = M.races_of("2026", "S", label), M.races_of("2022", "S", label)
                out[f"{label}-{pty}-{name}"] = {"share_2026": r3(ds(x)), "share_2022": r3(ds(y)), "change_points": r3(fn(x, y)),
                                                "interval": M.boot(fn, x, y)}
    # the as-coded reading must match the summary's own figures
    S = json.loads((RES / "summary.json").read_text(encoding="utf-8"))
    for pty in ("D", "R"):
        want = S["ie_digital_change"][f"t20-{pty}"]
        got = out[f"close-{pty}-as_coded"]
        assert abs(got["share_2026"] - want["share_2026"]) < 0.01 and abs(got["share_2022"] - want["share_2022"]) < 0.01, pty
        assert all(abs(a - b) < 0.05 for a, b in zip(got["interval"], want["interval"])), (pty, got["interval"], want["interval"])
        for c in ("2026", "2022"):
            assert abs(out[f"safe-{pty}-as_coded"][f"share_{c}"] - S["ie_mix"][f"{c}-S-safe-t20"][pty]["digital_of_ads_pct"]) < 0.01
    groups = raw["digital_coding_groups_senate_t20"]
    moved = {k: {"digital_dollars": sum(v.values()), "channel_or_stream_dollars": v["digital_channel"] + v["digital_stream"],
                 "generic_media_word_dollars": v["digital_mediaword"]} for k, v in groups.items()}
    return out, moved


def coverage(S, raw):
    rec, cy = S["reconciliation"], S["cycles"]
    c22 = rec["ie_2022"]["kept_house_senate"] / rec["ie_2022"]["committee_summary_all_offices"]
    c26 = rec["ie_2026"]["kept_house_senate_through_t20"] / rec["ie_2026"]["committee_summary_all_offices"]
    out = {"kept_to_summary_2022_pct": r3(100 * c22), "kept_to_summary_2026_t20_pct": r3(100 * c26),
           "summary_ratio_2026_to_2022": r3(rec["ie_2026"]["committee_summary_all_offices"] / rec["ie_2022"]["committee_summary_all_offices"])}
    for o in ("S", "H"):
        ratio = cy[f"2026-{o}"]["ie_t20"] / cy[f"2022-{o}"]["ie_t20"]
        out[f"file_ratio_{o}"] = r3(ratio)
        out[f"coverage_scaled_ratio_{o}"] = r3(ratio * c22 / c26)
    wf = raw["web_form_bands"]
    out["web_form_under_1m"] = {c: {"rows": wf[c]["under_10k"]["rows"] + wf[c]["10k_to_1m"]["rows"],
                                    "dollars": wf[c]["under_10k"]["dollars"] + wf[c]["10k_to_1m"]["dollars"]} for c in ("2026", "2022")}
    out["web_form_1m_or_more"] = {c: wf[c]["1m_or_more"] for c in ("2026", "2022")}
    return out


def end_dates(raw):
    d = raw["summary_end_dates_2026"]
    out = {}
    for o in ("S", "H"):
        for label in ("close", "safe"):
            rows = {g: d.get(f"{o}-{label}-{g}", {"candidates": 0, "disbursements": 0})
                    for g in ("through_14_oct_or_later", "through_30_sep_to_13_oct", "earlier")}
            n = sum(v["candidates"] for v in rows.values())
            m = sum(v["disbursements"] for v in rows.values())
            out[f"{o}-{label}"] = {"candidates": n, "disbursements": m,
                                   **{f"{g}_dollars_pct": r3(100 * v["disbursements"] / m) for g, v in rows.items()},
                                   **{f"{g}_candidates_pct": r3(100 * v["candidates"] / n) for g, v in rows.items()}}
    return out


def predictions(S):
    C, MED, OPP = S["concentration"], S["medians"], S["opposed"]
    rows = {"P1": (60, [C["2026-S-t20"]["interval_pct"]]), "P2": (50, [C["2026-H-t20"]["interval_pct"]]),
            "P3": (2, [MED["2026-S-summary-total"]["ratio_interval"]]),
            "P7": (50, [OPP[f"{c}-S-close-t20"][p]["interval_pct"] for c in ("2026", "2022") for p in ("D", "R")])}
    out = {}
    for k, (bar, ivs) in rows.items():
        assert S["predictions"][k]["verdict"].startswith("held")
        out[k] = {"bar": bar, "intervals": ivs, "interval_includes_bar": any(lo <= bar <= hi for lo, hi in ivs)}
    return out


def ie_to_candidate_2026(S):
    """A measure the protocol declared (2026 against 2022, with its fourth change: for 2026 only) and the first summary left out:
    independent spending through T-20 against candidates' total disbursements in the all-candidates summary, every race."""
    out = {}
    for o in ("S", "H"):
        keys = M.races_of("2026", o)
        d = sum(M.disb[k] for k in keys)
        assert round(sum(M.ie_tot[("t20", k)] for k in keys)) == S["cycles"][f"2026-{o}"]["ie_t20"]
        out[o] = {"ie_t20": S["cycles"][f"2026-{o}"]["ie_t20"], "candidate_disbursements": round(d), "ratio": r3(S["cycles"][f"2026-{o}"]["ie_t20"] / d)}
    return out


def main(out_dir=RES):
    S = json.loads((RES / "summary.json").read_text(encoding="utf-8"))
    raw = json.loads((RES / "after_review_raw.json").read_text(encoding="utf-8"))
    dig, moved = digital(raw)
    h = S["concentration"]["2026-H-t20"]
    out = {"note": "Post-review figures; see after-review-r1.json. Shares and points in percent, three decimals; intervals are the "
                   "protocol's percentile bootstrap, races resampled within class, 2000 replicates, seed 20261103.",
           "sweep_t20": sweep(), "protocol_sensitivity_counts": protocol_sensitivity(), "largest_close_race_t20": largest_close_race(),
           "year_differences_t20": year_differences(), "digital_senate_t20": dig, "digital_dollars_by_reason_senate_t20": moved,
           "coverage": coverage(S, raw), "summary_end_dates_2026": end_dates(raw), "held_predictions_interval_against_bar": predictions(S),
           "house_2026_new_lines_share_of_ie_t20_pct": r3(100 * h["not_classified_dollars"] / h["total_all_races"]),
           "ie_to_candidate_2026": ie_to_candidate_2026(S)}
    (Path(out_dir) / "after_review.json").write_text(json.dumps(out, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print("wrote after_review.json")


if __name__ == "__main__":
    main()
