#!/usr/bin/env python3
"""Check published derived counts. Does not recompute scores or bootstrap intervals.
Author: OpenAI Codex, November 2026. Python standard library only.
"""
import csv
import json
import math
from pathlib import Path

root = Path(__file__).resolve().parent
data = json.loads((root / "calibration.json").read_text())
control = data["control"]
assert sum(control["n_by_group"]) == 9994
assert sum(control["hits_pooled_by_group"]) == 100
print("Control: count, pooled FPR, length-matched FPR")
for n, fixed, matched in zip(control["n_by_group"], control["hits_pooled_by_group"], control["hits_matched_by_group"]):
    assert 0 <= fixed <= n and 0 <= matched <= n
    print(f"{n}: {100*fixed/n:.3f}%, {100*matched/n:.3f}%")

print("Recall: fixed count, matched count, denominator, change in percentage points")
for name, row in data["sets"].items():
    n = sum(row["n_by_group"])
    assert n == row["n"]
    fixed = sum(row["hits_fixed_line_by_group"])
    matched = sum(row["hits_own_line_by_group"])
    for size, a, b in zip(row["n_by_group"], row["hits_fixed_line_by_group"], row["hits_own_line_by_group"]):
        assert 0 <= a <= size and 0 <= b <= size
    for actual, expected in [(fixed/n, row["recall"]), (matched/n, row["matched_recall"]), ((matched-fixed)/n, row["change"])]:
        assert math.isclose(actual, expected, rel_tol=0, abs_tol=1e-14)
    assert (abs((matched-fixed)/n) >= .02) == row["M1"]
    print(f"{name}: {fixed}, {matched}, {n}, {100*(matched-fixed)/n:+.4f}")

rows = list(csv.DictReader((root / "fixed-label.csv").open()))
assert len(rows) == 16
assert len({(r['set'], r['label'], r['measure']) for r in rows}) == 16
for row in rows:
    assert math.isclose(float(row['rho'])**2, float(row['rho_squared']), abs_tol=1e-14)
print(f"Fixed-label table: {sum(r['no_sign_under_original_rule']=='True' for r in rows)}/16 cells marked no sign.")
print("PASS: derived-count arithmetic. Intervals, thresholds, pairing and raw inputs are not revalidated.")
