"""The fourth set of later figures, declared in after-review-r3.json before the population file was downloaded and before
any of them was computed: the Senate against voting-age residents, at every split of the close line from 5 to 15 points.
Writes results/after_review3.json from the stored race files and data/population_18plus.json, through tools/summarize.py's
own functions (same arithmetic, same bootstrap and seed) and tools/after_review2.py's split enumeration. Every other file
in results/ is read and not changed.

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

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

RES = ROOT / "results"
POP = json.loads((ROOT / "data" / "population_18plus.json").read_text(encoding="utf-8"))["states"]
SETS = (("2026", "S"), ("2022", "S"))
FEW = A2.FEW
TESTED = (9.5, 10)


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


def residents(keys, cycle):
    return sum(POP[k[2]][cycle] for k in keys)


def money(keys):
    return sum(M.ie_tot[("t20", k)] for k in keys)


def gap_fn(cycle):
    """Close races' share of the money minus their share of voting-age residents, in points, for resampled groups."""
    def fn(close, safe):
        m, p = money(close) + money(safe), residents(close, cycle) + residents(safe, cycle)
        if not m or not p:
            return None
        return 100 * money(close) / m - 100 * residents(close, cycle) / p
    return fn


def every_split():
    stored = json.loads((RES / "after_review2.json").read_text(encoding="utf-8"))["every_split_t20"]
    out = {}
    for c, o in SETS:
        rows = []
        mine = A2.splits(c, o)
        assert len(mine) == len(stored[f"{c}-{o}"]["splits"]), (c, o)
        for (lo, lo_incl, hi, close, safe), want in zip(mine, stored[f"{c}-{o}"]["splits"]):
            # the same splits as the third set, race for race
            assert (lo, lo_incl, hi, len(close), len(safe)) == (want["line_low"], want["line_low_included"],
                                                               want["line_high"], want["close_races"], want["safe_races"])
            assert sorted(k[2] for k in close) == want["close_states"]
            share_m = 100 * money(close) / (money(close) + money(safe))
            share_p = 100 * residents(close, c) / (residents(close, c) + residents(safe, c))
            assert round(share_m, 3) == want["share_of_money_pct"], (c, lo)
            ilo, ihi = M.boot(gap_fn(c), close, safe)
            few = min(len(close), len(safe)) < FEW
            rows.append({"line_low": lo, "line_low_included": lo_incl, "line_high": hi,
                         "close_races": len(close), "safe_races": len(safe), "close_states": want["close_states"],
                         "share_of_races_pct": want["share_of_races_pct"], "share_of_money_pct": want["share_of_money_pct"],
                         "share_of_residents_18plus_pct": r3(share_p), "ratio_to_residents": r3(share_m / share_p),
                         "gap_points": r3(share_m - share_p), "gap_interval_points": [ilo, ihi],
                         "gap_interval_excludes_zero": ilo > 0 or ihi < 0, "too_few_races_to_read": few})
        readable = [r for r in rows if not r["too_few_races_to_read"]]
        span = lambda rs: [[r["line_low"], r["line_low_included"], r["line_high"]] for r in rs]  # noqa: E731
        at = {f"{t:g}": next(r for r in rows if A2.line_in(t, r["line_low"], r["line_low_included"], r["line_high"]))
              for t in TESTED}
        out[f"{c}-{o}"] = {
            "splits": rows,
            "at_line": {t: {k: r[k] for k in ("close_races", "share_of_races_pct", "share_of_money_pct",
                                               "share_of_residents_18plus_pct", "ratio_to_residents", "gap_points",
                                               "gap_interval_points", "gap_interval_excludes_zero", "too_few_races_to_read")}
                        for t, r in at.items()},
            "smallest_ratio_to_residents": min(r["ratio_to_residents"] for r in rows),
            "smallest_ratio_to_residents_readable": min(r["ratio_to_residents"] for r in readable),
            "splits_gap_interval_includes_zero": span([r for r in rows if not r["gap_interval_excludes_zero"]]),
            "readable_splits_gap_interval_includes_zero": span([r for r in readable if not r["gap_interval_excludes_zero"]]),
            "readable_splits": len(readable),
        }
    return out


def texas():
    keys = A2.classified("2026", "S")
    tx = [k for k in keys if k[2] == "TX"]
    assert len(tx) == 1 and len(keys) == 35
    return {"share_of_residents_18plus_pct": r3(100 * residents(tx, "2026") / residents(keys, "2026")),
            "share_of_labelled_money_pct": r3(100 * money(tx) / money(keys)), "labelled_races": len(keys)}


def main(out_dir=RES):
    out = {"note": ("Fourth set of later figures; see after-review-r3.json. Senate only: close races' share of the resident "
                    "population aged 18 and over of their states (1 July 2025 for 2026, 1 July 2021 for 2022), beside their "
                    "share of seats and of independent spending through 20 days before the vote, at every split of the "
                    "third set. Gap: money share minus resident share, in points; its interval is the protocol's percentile "
                    "bootstrap, races resampled within close and within safe, 2000 replicates, seed 20261103, both shares "
                    "recomputed in each replicate. Shares and points in percent, three decimals."),
           "every_split_t20": every_split(), "texas_2026": texas(), "too_few_races_below": FEW}
    (Path(out_dir) / "after_review3.json").write_text(json.dumps(out, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print("wrote after_review3.json")


if __name__ == "__main__":
    main()
