"""Reconciliations against the FEC's own summaries. Writes results/reconciliation.json. The last line is the verdict.

Usage: python3 -I -B tools/checks.py <fec raw dir> <results dir>

Candidate spending: operating spending kept by the pipeline, whole of each cycle, against total disbursements in the
all-candidates summary. A ratio far above 1 would mean double counting. Below 1 is expected, because total disbursements also
hold transfers, refunds and loan repayments, which are not operating spending.
Independent spending: 2022 kept rows, House and Senate, against the committee summary. The summary also holds presidential
spending and reports that are not 24 or 48 hour reports, so a ratio above 1 would mean double counting.
Added after the first close-against-safe figures were seen (listed in after-results-r1.json): the same comparison for 2026,
through 30 September and through 14 October, allowing 1.10 because some reports are not in the summary yet, and a positive
control for every threshold (rows counted twice, and for 2022 the web-form rows put back), each of which must trip it.
"""
import io
import json
import sys
import zipfile
from pathlib import Path

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


def weball(path):
    out = {}
    with zipfile.ZipFile(path) as z:
        with z.open(z.namelist()[0]) as f:
            for l in io.TextIOWrapper(f, encoding="latin-1"):
                p = l.rstrip("\n").split("|")
                try:
                    out[p[0]] = {"disb": float(p[7] or 0), "end": p[27], "state": p[18]}
                except (ValueError, IndexError):
                    continue
    return out


def main():
    raw, res = Path(sys.argv[1]), Path(sys.argv[2])
    out = {}
    for cycle, cfg in P.PROTOCOL["cycles"].items():
        yy = cycle[2:]
        cands = P.read_candidates(raw / f"cn{yy}.zip", cycle)
        cmtes = P.read_committees(raw / f"ccl{yy}.zip", cands, cycle)
        op = P.read_oppexp(raw / f"oppexp{yy}.zip", cmtes, cfg["window_start"], f"{cycle}-12-31")
        ours = {"H": 0.0, "S": 0.0}
        for k, v in op["amounts"].items():
            ours[k[0]] += v
        summ = weball(raw / f"weball{yy}.zip")
        theirs = {"H": 0.0, "S": 0.0}
        ends = {}
        for cid, row in summ.items():
            if cid in cands:
                theirs[cands[cid].office] += row["disb"]
                ends[row["end"]] = ends.get(row["end"], 0) + 1
        out[cycle] = {"candidate_spending_on_file": {k: round(v) for k, v in ours.items()},
                      "total_disbursements_in_summary": {k: round(v) for k, v in theirs.items()},
                      "ratio": {k: round(ours[k] / theirs[k], 3) for k in ours},
                      "summary_candidates": sum(ends.values()),
                      "summary_coverage_end_top": sorted(ends.items(), key=lambda t: -t[1])[:4]}
    # independent spending, 2022, against the committee summary
    cands = P.read_candidates(raw / "cn22.zip", "2022")
    cfg = P.PROTOCOL["cycles"]["2022"]
    ie = P.read_ie(raw / "independent_expenditure_2022.csv", cands, cfg["window_start"], "2022-12-31", "2022-12-31")
    kept = sum(ie["t0"].values())
    web22 = ie["web_form_dollars_after_duplicates"]
    summary = 0.0
    with zipfile.ZipFile(raw / "webk22.zip") as z:
        with z.open(z.namelist()[0]) as f:
            for l in io.TextIOWrapper(f, encoding="latin-1"):
                p = l.rstrip("\n").split("|")
                summary += float(p[23] or 0)
    out["ie_2022"] = {"kept_house_senate": round(kept), "committee_summary_all_offices": round(summary),
                      "ratio": round(kept / summary, 3), "web_form_dollars_excluded": round(ie["web_form_dollars"]),
                      "web_form_rows_excluded": ie["counts"]["web_form_rows"]}
    # independent spending, 2026, on the same days as the committee summary's reports (through 30 September)
    cands = P.read_candidates(raw / "cn26.zip", "2026")
    cfg = P.PROTOCOL["cycles"]["2026"]
    ie = P.read_ie(raw / "independent_expenditure_2026.csv", cands, cfg["window_start"], cfg["election_day"], cfg["t20"], "2026-09-30")
    kept = sum(ie["t34"].values())
    kept_t20 = sum(ie["t20"].values())
    summary, ends = 0.0, {}
    with zipfile.ZipFile(raw / "webk26.zip") as z:
        with z.open(z.namelist()[0]) as f:
            for l in io.TextIOWrapper(f, encoding="latin-1"):
                p = l.rstrip("\n").split("|")
                summary += float(p[23] or 0)
                if float(p[23] or 0) > 0:
                    ends[p[26]] = ends.get(p[26], 0) + 1
    out["ie_2026"] = {"kept_house_senate_through_30_sep": round(kept), "committee_summary_all_offices": round(summary),
                      "ratio": round(kept / summary, 3), "kept_house_senate_through_t20": round(kept_t20),
                      "ratio_t20": round(kept_t20 / summary, 3),
                      "summary_coverage_end_top": sorted(ends.items(), key=lambda t: -t[1])[:4]}
    print(json.dumps(out)[:1500])
    problems = []
    for cycle in ("2022", "2026"):
        for k, v in out[cycle]["ratio"].items():
            if v > 1.02:
                problems.append(f"{cycle} {k} candidate spending ratio {v} above the summary")
    if out["ie_2022"]["ratio"] > 1.02:
        problems.append("independent spending above the committee summary")
    for k in ("ratio", "ratio_t20"):
        if out["ie_2026"][k] > 1.10:
            problems.append(f"2026 independent spending {out['ie_2026'][k]} of the committee summary ({k}), above the 1.10 allowed for reports not yet in the summary")
    # positive controls: a planted fault must trip each threshold, or the check proves nothing
    ie22 = out["ie_2022"]
    controls = {
        "candidate_2022_rows_counted_twice": max(2 * v for v in out["2022"]["ratio"].values()) > 1.02,
        "candidate_2026_rows_counted_twice": max(2 * v for v in out["2026"]["ratio"].values()) > 1.02,
        "ie_2022_rows_counted_twice": 2 * ie22["ratio"] > 1.02,
        "ie_2022_web_form_rows_kept": (ie22["kept_house_senate"] + web22) / ie22["committee_summary_all_offices"] > 1.02,
        "ie_2026_rows_counted_twice": 2 * out["ie_2026"]["ratio_t20"] > 1.10,
    }
    out["positive_controls_trip"] = controls
    (res / "reconciliation.json").write_text(json.dumps(out, indent=1) + "\n", encoding="utf-8")
    problems += [f"positive control {k} did not trip its threshold" for k, v in controls.items() if not v]
    print("positive controls:", controls)
    print("VERDICT:", "PASS" if not problems else "FAIL " + "; ".join(problems))


if __name__ == "__main__":
    main()
