"""Compute every figure on the page from the aggregate CSVs, score the predictions and write results/summary.json.

Usage: python3 -I -B tools/summarize.py
Reads only results/*.csv, data/prior_margins.json and the protocol files, so it runs with no download.
Shares and points are stored to three decimals so the page rounds once (after the first figures, the page rounded values
already stored to one decimal again; see after-results-r1.json).
"""
import collections
import csv
import json
import random
import statistics
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
RES = ROOT / "results"
PROTOCOL = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
PRED = json.loads((ROOT / "predictions-r1.json").read_text(encoding="utf-8"))
B = PROTOCOL["intervals"]["replicates"]
SEED = PROTOCOL["intervals"]["seed"]
ADS = ("media", "digital", "mail")


def load(name):
    with open(RES / f"{name}.csv", encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))


RACES = load("races")
IE = load("race_ie")
SPEND = load("race_spend")
DISB = load("race_disb")


def rkey(r):
    return (r["cycle"], r["office"], r["state"], r["district"])


race = {rkey(r): r for r in RACES}
ie_tot = collections.Counter()      # (window, race) -> dollars
ie_party = collections.Counter()    # (window, race, party, direction)
ie_cat = collections.Counter()      # (window, race, party, category)
for r in IE:
    k = rkey(r)
    d = float(r["dollars"])
    ie_tot[(r["window"], k)] += d
    ie_party[(r["window"], k, r["party"], r["direction"])] += d
    ie_cat[(r["window"], k, r["party"], r["category"])] += d
spend = collections.Counter()       # (race, party, category)
spend_tot = collections.Counter()   # race
for r in SPEND:
    k = rkey(r)
    d = float(r["dollars"])
    spend[(k, r["party"], r["category"])] += d
    spend_tot[k] += d
disb = collections.Counter()
disb_party = collections.Counter()
for r in DISB:
    disb[rkey(r)] += float(r["total_disbursements"])
    disb_party[(rkey(r), r["party"])] += float(r["total_disbursements"])


def races_of(cycle, office, label=None, close_state=None):
    out = []
    for k, r in race.items():
        if k[0] != cycle or k[1] != office:
            continue
        if label and r["label"] != label:
            continue
        if close_state is not None and int(r["close_state"]) != close_state:
            continue
        out.append(k)
    return sorted(out)


def boot(fn, *groups):
    rng = random.Random(SEED)
    vals = []
    for _ in range(B):
        sampled = [rng.choices(g, k=len(g)) if g else g for g in groups]
        v = fn(*sampled)
        if v is not None:
            vals.append(v)
    vals.sort()
    if not vals:
        return [None, None]
    return [round(vals[int(0.025 * len(vals))], 3), round(vals[int(0.975 * len(vals)) - 1], 3)]


def share_close(window):
    def fn(close, safe):
        a = sum(ie_tot[(window, k)] for k in close)
        b = sum(ie_tot[(window, k)] for k in safe)
        return 100 * a / (a + b) if a + b else None
    return fn


def concentration(cycle, office, window, close=None, safe=None):
    close = close if close is not None else races_of(cycle, office, "close")
    safe = safe if safe is not None else races_of(cycle, office, "safe")
    fn = share_close(window)
    allk = races_of(cycle, office)
    total = sum(ie_tot[(window, k)] for k in allk)
    nc = [k for k in allk if race[k]["label"] == "not_classified"]
    amounts = sorted((ie_tot[(window, k)] for k in close + safe), reverse=True)
    return {"close_races": len(close), "safe_races": len(safe), "not_classified_races": len(nc),
            "share_of_races_pct": round(100 * len(close) / (len(close) + len(safe)), 3) if close or safe else None,
            "share_of_money_pct": round(fn(close, safe), 3) if close or safe else None,
            "interval_pct": boot(fn, close, safe) if close and safe else None,
            "total_all_races": round(total), "close_dollars": round(sum(ie_tot[(window, k)] for k in close)),
            "safe_dollars": round(sum(ie_tot[(window, k)] for k in safe)),
            "not_classified_dollars": round(sum(ie_tot[(window, k)] for k in nc)),
            "top5_share_pct": round(100 * sum(amounts[:5]) / sum(amounts), 3) if sum(amounts) else None,
            "races_with_none": sum(1 for a in amounts if a <= 0)}


def median_ratio(values_close, values_safe):
    def fn(c, s):
        a, b = statistics.median(c), statistics.median(s)
        return a / b if b else None
    a, b = statistics.median(values_close), statistics.median(values_safe)
    return {"median_close": round(a), "median_safe": round(b), "ratio": round(a / b, 2) if b else None,
            "ratio_interval": boot(fn, values_close, values_safe)}


def opposed(cycle, office, label, window):
    out = {}
    keys = races_of(cycle, office, label)
    for pty in ("D", "R"):
        def fn(g):
            o = sum(ie_party[(window, k, pty, "O")] for k in g)
            s = sum(ie_party[(window, k, pty, "S")] for k in g)
            return 100 * o / (o + s) if o + s else None
        o = sum(ie_party[(window, k, pty, "O")] for k in keys)
        s = sum(ie_party[(window, k, pty, "S")] for k in keys)
        out[pty] = {"oppose": round(o), "support": round(s), "oppose_share_pct": round(fn(keys), 3) if o + s else None,
                    "interval_pct": boot(fn, keys) if keys else None}
    return out


def direction_of_help(cycle, office, label, window):
    """Dollars aimed at each major party's candidates, split by direction, same arithmetic for both."""
    keys = races_of(cycle, office, label)
    return {pty: {d: round(sum(ie_party[(window, k, pty, d)] for k in keys)) for d in ("S", "O")} for pty in ("D", "R", "other")}


def mix(keys, party):
    tot = collections.Counter()
    for k in keys:
        for cat in ("media", "digital", "mail", "fundraising", "staff", "consulting", "polling", "field", "compliance", "overhead", "other"):
            tot[cat] += spend[(k, party, cat)]
    t = sum(tot.values())
    if not t:
        return None
    return {"dollars": round(t), "shares_pct": {c: round(100 * v / t, 3) for c, v in tot.items()},
            "paid_ads_pct": round(100 * sum(tot[c] for c in ADS) / t, 3),
            "digital_of_ads_pct": round(100 * tot["digital"] / sum(tot[c] for c in ADS), 3) if sum(tot[c] for c in ADS) else None}


def mix_share(keys, party, cats):
    a = sum(spend[(k, party, c)] for k in keys for c in cats)
    t = sum(spend[(k, party, c)] for k in keys for c in ("media", "digital", "mail", "fundraising", "staff", "consulting", "polling", "field", "compliance", "overhead", "other"))
    return 100 * a / t if t else None


def mix_diff(cycle, office, party, cats):
    c, s = races_of(cycle, office, "close"), races_of(cycle, office, "safe")
    def fn(x, y):
        a, b = mix_share(x, party, cats), mix_share(y, party, cats)
        return a - b if a is not None and b is not None else None
    v = fn(c, s)
    return {"diff_points": round(v, 3) if v is not None else None, "interval": boot(fn, c, s)}


def ie_mix(keys, party, window):
    tot = collections.Counter()
    for k in keys:
        for cat in ("media", "digital", "mail", "field", "fundraising", "staff", "consulting", "polling", "compliance", "overhead", "other"):
            tot[cat] += ie_cat[(window, k, party, cat)]
    t = sum(tot.values())
    ads = sum(tot[c] for c in ADS)
    return {"dollars": round(t), "digital_of_ads_pct": round(100 * tot["digital"] / ads, 3) if ads else None,
            "shares_pct": {c: round(100 * v / t, 3) for c, v in tot.most_common()} if t else None}


def main():
    S = {"coverage": json.loads((RES / "coverage.json").read_text(encoding="utf-8")),
         "reconciliation": json.loads((RES / "reconciliation.json").read_text(encoding="utf-8"))}
    S["race_counts"] = {c: {o: collections.Counter(race[k]["label"] for k in races_of(c, o)) for o in ("S", "H")} for c in ("2026", "2022")}
    S["concentration"] = {f"{c}-{o}-{w}": concentration(c, o, w) for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H"))
                          for w in ("t20", "t0", "t20_general")}
    # sensitivity: under 5 points against 20 or more
    sens = {}
    for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H")):
        keys = [k for k in races_of(c, o) if race[k]["prior_margin"] != ""]
        close5 = [k for k in keys if float(race[k]["prior_margin"]) < 5]
        safe20 = [k for k in keys if float(race[k]["prior_margin"]) >= 20]
        sens[f"{c}-{o}-t20"] = concentration(c, o, "t20", close5, safe20)
    S["sensitivity"] = sens
    S["medians"] = {}
    for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H")):
        cl, sf = races_of(c, o, "close"), races_of(c, o, "safe")
        S["medians"][f"{c}-{o}-ie-t20"] = median_ratio([ie_tot[("t20", k)] for k in cl], [ie_tot[("t20", k)] for k in sf])
        S["medians"][f"{c}-{o}-itemized-mid-year"] = median_ratio([spend_tot[k] for k in cl], [spend_tot[k] for k in sf])
    for o in ("S", "H"):
        cl, sf = races_of("2026", o, "close"), races_of("2026", o, "safe")
        S["medians"][f"2026-{o}-summary-total"] = median_ratio([disb[k] for k in cl], [disb[k] for k in sf])
    S["opposed"] = {f"{c}-{o}-{l}-{w}": opposed(c, o, l, w) for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H"))
                    for l in ("close", "safe") for w in ("t20", "t0")}
    S["direction"] = {f"{c}-{o}-{l}-t20": direction_of_help(c, o, l, "t20") for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H"))
                      for l in ("close", "safe")}
    S["mix"] = {}
    for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H")):
        for l in ("close", "safe"):
            S["mix"][f"{c}-{o}-{l}"] = {p: mix(races_of(c, o, l), p) for p in ("D", "R")}
    for c in ("2026", "2022"):
        S["mix"][f"{c}-H-all"] = {p: mix(races_of(c, "H"), p) for p in ("D", "R")}
    S["mix_diff"] = {f"{c}-{o}-{name}-{p}": mix_diff(c, o, p, cats) for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H"))
                     for name, cats in (("ads", ADS), ("fundraising", ("fundraising",)), ("staff", ("staff",))) for p in ("D", "R")}
    S["ie_mix"] = {}
    for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H")):
        for l in ("close", "safe"):
            for w in ("t20", "t0"):
                S["ie_mix"][f"{c}-{o}-{l}-{w}"] = {p: ie_mix(races_of(c, o, l), p, w) for p in ("D", "R")}
    # the digital share of independent paid ads, Senate close races, 2026 against 2022, with an interval
    S["ie_digital_change"] = {}
    for w in ("t20", "t0"):
        for pty in ("D", "R"):
            def dshare(g, p=pty, wd=w):
                ads = sum(ie_cat[(wd, k, p, c)] for k in g for c in ADS)
                return 100 * sum(ie_cat[(wd, k, p, "digital")] for k in g) / ads if ads else None
            def fn(x, y):
                a, b = dshare(x), dshare(y)
                return a - b if a is not None and b is not None else None
            x, y = races_of("2026", "S", "close"), races_of("2022", "S", "close")
            S["ie_digital_change"][f"{w}-{pty}"] = {"share_2026": round(dshare(x), 3), "share_2022": round(dshare(y), 3),
                                                    "change_points": round(fn(x, y), 3), "interval": boot(fn, x, y)}
    # how much of each class's independent spending is coded to the general election
    S["general_share"] = {}
    for c, o in (("2026", "S"), ("2022", "S"), ("2026", "H")):
        for l in ("close", "safe"):
            keys = races_of(c, o, l)
            a, t = sum(ie_tot[("t20_general", k)] for k in keys), sum(ie_tot[("t20", k)] for k in keys)
            S["general_share"][f"{c}-{o}-{l}"] = round(100 * a / t, 3) if t else None
    # 2026 against 2022
    S["cycles"] = {}
    for c in ("2026", "2022"):
        for o in ("S", "H"):
            keys = races_of(c, o)
            S["cycles"][f"{c}-{o}"] = {"races": len(keys), "itemized_mid_year": round(sum(spend_tot[k] for k in keys)),
                                       "ie_t20": round(sum(ie_tot[("t20", k)] for k in keys)),
                                       "ie_t0": round(sum(ie_tot[("t0", k)] for k in keys))}
    # close states
    S["states"] = {}
    for c in ("2026", "2022"):
        allk = [k for k in race if k[0] == c]
        cs = sorted({k[2] for k in allk if int(race[k]["close_state"]) == 1})
        row = {"close_states": cs}
        for o in ("S", "H"):
            for flag, name in ((1, "close"), (0, "other")):
                keys = races_of(c, o, None, flag)
                it = [spend_tot[k] for k in keys]
                ie = [ie_tot[("t20", k)] for k in keys]
                row[f"{o}-{name}"] = {"races": len(keys), "itemized_mean": round(statistics.mean(it)) if it else None,
                                      "ie_t20_mean": round(statistics.mean(ie)) if ie else None,
                                      "ie_t20_total": round(sum(ie)), "ie_t20_median": round(statistics.median(ie)) if ie else None}
        S["states"][c] = row
    # Michigan, the worked example
    mi = {}
    sk = ("2026", "S", "MI", "00")
    mi["senate"] = {"prior_margin": float(race[sk]["prior_margin"]), "label": race[sk]["label"],
                    "president_margin": float(race[sk]["state_president_margin"]),
                    "ie_t20": round(ie_tot[("t20", sk)]), "ie_t0": round(ie_tot[("t0", sk)]),
                    "summary_total": round(disb[sk]),
                    "summary_by_party": {p: round(disb_party[(sk, p)]) for p in ("D", "R")},
                    "by_party_t0": {p: {d: round(ie_party[("t0", sk, p, d)]) for d in ("S", "O")} for p in ("D", "R")},
                    "by_party_t20": {p: {d: round(ie_party[("t20", sk, p, d)]) for d in ("S", "O")} for p in ("D", "R")},
                    "mix": {p: mix([sk], p) for p in ("D", "R")},
                    "rank_in_senate_t0": 1 + sum(1 for k in races_of("2026", "S") if ie_tot[("t0", k)] > ie_tot[("t0", sk)])}
    hk = [k for k in races_of("2026", "H") if k[2] == "MI"]
    mi["house"] = [{"district": k[3], "prior_margin": float(race[k]["prior_margin"]), "label": race[k]["label"],
                    "ie_t20": round(ie_tot[("t20", k)]), "ie_t0": round(ie_tot[("t0", k)]), "summary_total": round(disb[k])}
                   for k in hk]
    S["michigan"] = mi
    S["senate_table"] = {c: sorted(({"state": k[2], "prior_margin": float(race[k]["prior_margin"]) if race[k]["prior_margin"] != "" else None,
                                     "label": race[k]["label"], "ie_t20": round(ie_tot[("t20", k)]), "ie_t0": round(ie_tot[("t0", k)]),
                                     "itemized_mid_year": round(spend_tot[k]), "summary_total": round(disb[k])}
                                    for k in races_of(c, "S")), key=lambda r: -r["ie_t20"]) for c in ("2026", "2022")}
    # predictions, scored as declared and with the changes named
    con = S["concentration"]
    obs = {}
    def verdict(ok):
        return "held" if ok else "missed"
    a = con["2026-S-t20"]
    obs["P1"] = (verdict(a["share_of_money_pct"] >= 60 and a["share_of_races_pct"] <= 40), f"{a['share_of_money_pct']:.1f}% of money, {a['share_of_races_pct']:.1f}% of races")
    a = con["2026-H-t20"]
    obs["P2"] = (verdict(a["share_of_money_pct"] >= 50), f"{a['share_of_money_pct']:.1f}%")
    a = S["medians"]["2026-S-summary-total"]
    obs["P3"] = (verdict(a["ratio"] >= 2) + " (on summary totals, Change 4)", f"ratio {a['ratio']}")
    d = S["mix_diff"]
    obs["P4"] = (verdict(d["2026-S-ads-D"]["diff_points"] >= 5 and d["2026-S-ads-R"]["diff_points"] >= 5) + " (at 30 June, Change 4)",
                 f"D {d['2026-S-ads-D']['diff_points']:.1f}, R {d['2026-S-ads-R']['diff_points']:.1f} points")
    obs["P5"] = (verdict(abs(d["2026-S-fundraising-D"]["diff_points"]) < 5 and abs(d["2026-S-fundraising-R"]["diff_points"]) < 5) + " (at 30 June, Change 4)",
                 f"D {d['2026-S-fundraising-D']['diff_points']:.1f}, R {d['2026-S-fundraising-R']['diff_points']:.1f} points")
    m = S["mix"]
    g = {p: m["2026-S-close"][p]["digital_of_ads_pct"] - m["2022-S-close"][p]["digital_of_ads_pct"] for p in ("D", "R")}
    obs["P6"] = (verdict(g["D"] >= 3 and g["R"] >= 3) + " (at 30 June, Change 4)", f"D {g['D']:+.1f}, R {g['R']:+.1f} points")
    op = S["opposed"]
    vals = [op[f"{c}-S-close-t20"][p]["oppose_share_pct"] for c in ("2026", "2022") for p in ("D", "R")]
    obs["P7"] = (verdict(all(v > 50 for v in vals)), "2026 D, R; 2022 D, R: " + ", ".join(f"{v:.1f}%" for v in vals))
    cy = S["cycles"]
    obs["P8"] = (verdict(cy["2026-S"]["itemized_mid_year"] > cy["2022-S"]["itemized_mid_year"]) + " (at 30 June, Change 4)",
                 f"US${cy['2026-S']['itemized_mid_year'] / 1e6:.0f} million against US${cy['2022-S']['itemized_mid_year'] / 1e6:.0f} million")
    other = {f"{c} {p}": round(100 * sum(spend[(k, p, "other")] for k in race if k[0] == c)
                               / sum(spend[(k, p, cat)] for k in race if k[0] == c for cat in ("media", "digital", "mail", "fundraising", "staff", "consulting", "polling", "field", "compliance", "overhead", "other")), 1)
             for c in ("2026", "2022") for p in ("D", "R")}
    obs["P9"] = (verdict(max(other.values()) <= 15), other)
    a = S["medians"]["2026-H-ie-t20"]
    obs["P10"] = (verdict(a["median_safe"] < 10000) + " (safe bet)", f"median US${a['median_safe']:,}")
    S["predictions"] = {p["id"]: {"text": p["text"], "verdict": obs[p["id"]][0], "observed": obs[p["id"]][1]} for p in PRED["predictions"]}
    (RES / "summary.json").write_text(json.dumps(S, indent=1, sort_keys=True, default=dict) + "\n", encoding="utf-8")
    print("wrote summary.json")


if __name__ == "__main__":
    main()
