"""Changes decided after the results (declared on the page; results/summary.json stays frozen). Writes
results/changes-r1.json from results/geometry.jsonl, cache/*.jsonl and results/change2-units.json.

Intervals that allow for the table: 95% intervals that allow for the table. Each of the 200 tables gives three charts that share a title, unit
  and category names, so charts are not independent draws; the frozen Wilson intervals treat them as if they were.
  Wilson interval on the effective sample size: n divided by the design effect, the design effect being the variance of
  the proportion with tables as clusters (ratio estimator) over its variance with charts independent, floored at 1 so
  the interval is never narrower than the declared Wilson one. At 0 or all of n the design effect cannot be estimated
  and is taken as 1. (A percentile bootstrap over tables came out narrower than Wilson near 0% and 100%, so it is not
  used.) The population these describe: current Statistics Canada tables that
  can give all three charts, drawn with these three chart specifications.
Unit check: the rates again without the 17 charts whose categories carry different units (tools/unit_audit.py).
Right type: a "right type" catch rate beside the declared "either" rate: a defective chart counts as caught only if the
  model flagged a defect type the chart actually has.
Also read after the results: the paired comparison on subtle overlaps (counts of disagreeing charts and of the tables
  they come from; no chart-level test, since a table's charts are not independent) and the charts with a label at
  least 80% outside the image, with whether each reply names that label.

Usage: python3 -I -B tools/changes.py   (last line printed is the verdict)
"""
import json
import math
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
MODELS = ("claude-sonnet-5-5", "gpt-6.1-sol")
Z = 1.96


def load():
    G = [json.loads(x) for x in (ROOT / "results" / "geometry.jsonl").read_text(encoding="utf-8").splitlines() if x.strip()]
    A = {}
    for m in MODELS:
        A[m] = {}
        for x in (ROOT / "cache" / f"{m}.jsonl").read_text(encoding="utf-8").splitlines():
            if x.strip():
                r = json.loads(x)
                if r["error"] is None:
                    A[m][r["chart"]] = r["parsed"]
    return G, A


def anyd(r):
    return r["overlap"] or r["clipped"]


def measures(rows, A):
    """Counts (k, n) for each reported rate, over a list of geometry records (repeats allowed)."""
    out = {}

    def add(key, k, n):
        out[key] = (out.get(key, (0, 0))[0] + k, out.get(key, (0, 0))[1] + n)

    for r in rows:
        c = r["chart"]
        add("truth any", int(anyd(r)), 1)
        add("truth overlap", int(r["overlap"]), 1)
        add("truth clipped", int(r["clipped"]), 1)
        for m in MODELS:
            a = A[m][c]
            for t in ("overlap", "clipped"):
                if r[t]:
                    add(f"{m} {t} catch", int(a[t]), 1)
                else:
                    add(f"{m} {t} false_alarm", int(a[t]), 1)
            if anyd(r):
                add(f"{m} any catch", int(a["overlap"] or a["clipped"]), 1)
                add(f"{m} any right_type", int((r["overlap"] and a["overlap"]) or (r["clipped"] and a["clipped"])), 1)
            else:
                add(f"{m} any false_alarm", int(a["overlap"] or a["clipped"]), 1)
            if r["overlap"] and not r["overlap_clear"]:
                add(f"{m} small_overlap catch", int(a["overlap"]), 1)
    return out


def wilson(k, n, z=Z):
    if n <= 0:
        return [float("nan"), float("nan")]
    p = k / n
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * math.sqrt(max(p * (1 - p) / n + z * z / (4 * n * n), 0.0)) / d
    return [max(0.0, c - h), min(1.0, c + h)]


def design_effect(per_table):
    """per_table: list of (k_i, n_i) for tables with n_i > 0. Ratio-estimator variance with tables as clusters, over
    the variance with charts independent. None when it cannot be estimated (0 or all of n, or one table)."""
    K, N, T = sum(k for k, _ in per_table), sum(n for _, n in per_table), len(per_table)
    p = K / N
    if K in (0, N) or T < 2:
        return None
    v_cl = T / (T - 1) * sum((k - p * n) ** 2 for k, n in per_table) / N ** 2
    return v_cl / (p * (1 - p) / N)


def main():
    G, A = load()
    by_table = {}
    for r in G:
        by_table.setdefault(r["productId"], []).append(r)
    tables = sorted(by_table)
    assert len(tables) == 200 and all(len(v) == 3 for v in by_table.values())
    point = measures(G, A)
    per = {t: measures(by_table[t], A) for t in tables}
    change1 = {}
    for key, (kk, nn) in point.items():
        pt = [per[t][key] for t in tables if key in per[t] and per[t][key][1] > 0]
        deff = design_effect(pt)
        used = max(deff, 1.0) if deff is not None else 1.0
        n_eff = nn / used
        change1[key] = {"k": kk, "n": nn, "rate": kk / nn, "tables": len(pt),
                        "design_effect": None if deff is None else round(deff, 4), "n_effective": round(n_eff, 1),
                        "ci95_tables": wilson(kk / nn * n_eff, n_eff), "ci95_wilson": wilson(kk, nn)}
        lo, hi = change1[key]["ci95_tables"]
        wl, wh = change1[key]["ci95_wilson"]
        assert lo <= wl + 1e-12 and hi >= wh - 1e-12, key
    units = json.loads((ROOT / "results" / "change2-units.json").read_text(encoding="utf-8"))
    mixed = {c for c, v in units["charts"].items() if v["mixed"]}
    assert len(mixed) == 17
    kept = [r for r in G if r["chart"] not in mixed]
    change2 = {k: {"k": v[0], "n": v[1], "rate": v[0] / v[1]} for k, v in measures(kept, A).items()}
    change2["_charts_left_out"] = sorted(mixed)
    small = [r["chart"] for r in G if r["overlap"] and not r["overlap_clear"]]
    cl, gp = MODELS
    b = sum(1 for c in small if A[cl][c]["overlap"] and not A[gp][c]["overlap"])
    c_ = sum(1 for c in small if A[gp][c]["overlap"] and not A[cl][c]["overlap"])
    disagree = [c for c in small if A[cl][c]["overlap"] != A[gp][c]["overlap"]]
    paired = {"charts": len(small), "tables": len({c.rsplit("-", 1)[0] for c in small}),
              "only_claude_flagged": b, "only_gpt_flagged": c_,
              "disagreeing_tables": len({c.rsplit("-", 1)[0] for c in disagree})}
    off = []
    for r in G:
        for x in r["clips"]:
            if x["outside_frac"] >= 0.8:
                kind = r["texts"][x["i"]]["kind"]
                words = {"ylabel": ("y-axis label", "y axis label", "y label", r["texts"][x["i"]]["text"].lower()),
                         "legend": ("legend",)}.get(kind, (r["texts"][x["i"]]["text"].lower(),))
                off.append({"chart": r["chart"], "kind": kind, "outside_frac": x["outside_frac"],
                            **{m + " named it": bool(A[m][r["chart"]]["clipped"]) and any(
                                w in str(A[m][r["chart"]].get("clipped_where", "")).lower() for w in words) for m in MODELS},
                            **{m: bool(A[m][r["chart"]]["clipped"]) for m in MODELS},
                            **{m + " where": A[m][r["chart"]].get("clipped_where", "") for m in MODELS}})
                break
    res = {"note": "Changes decided after the results; results/summary.json is the frozen scoring.",
           "change1_table_intervals": {"method": "Wilson on n / design effect (tables as clusters), design effect floored at 1",
                                       "unit": "table (3 charts each)", "rates": change1},
           "change2_without_mixed_units": change2, "change3_right_type": {m: change1[f"{m} any right_type"] for m in MODELS},
           "small_overlaps_paired": paired, "labels_mostly_off_image": off}
    (ROOT / "results" / "changes-r1.json").write_text(json.dumps(res, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    for k in ("truth any", "claude-sonnet-5-5 any catch", "gpt-6.1-sol any catch", "claude-sonnet-5-5 any false_alarm",
              "gpt-6.1-sol any false_alarm", "claude-sonnet-5-5 any right_type", "gpt-6.1-sol any right_type",
              "claude-sonnet-5-5 small_overlap catch", "gpt-6.1-sol small_overlap catch"):
        v = change1[k]
        print(f"{k}: {v['k']}/{v['n']} deff {v['design_effect']} tables-CI {100 * v['ci95_tables'][0]:.1f} to "
              f"{100 * v['ci95_tables'][1]:.1f} (Wilson {100 * v['ci95_wilson'][0]:.1f} to {100 * v['ci95_wilson'][1]:.1f}); "
              f"without mixed units {change2[k]['k']}/{change2[k]['n']}")
    print("paired small overlaps:", paired)
    print("labels mostly off image:", [(o["chart"], o["kind"], o[cl], o[gp], o[cl + " named it"], o[gp + " named it"])
                                       for o in off])
    print("VERDICT: PASS")


if __name__ == "__main__":
    main()
