"""Scores persona against record: multi-category Brier score per person and question (probabilities
renormalised), paired by person; bootstrap 95% interval of the mean difference (persona - record),
2000 draws, seed 7. Usage: score_panel.py <people.json> <persona.jsonl> <record.jsonl> [primary questions comma-separated]"""
import json, sys, numpy as np
D = json.load(open(sys.argv[1])); P = {p["id"]: p for p in D["people"]}; Q = ["happy", "satfin", "finalter", "health"]
def load(f):
    out = {}
    for l in open(f):
        r = json.loads(l)
        if not r["p"] or len(r["p"]) != len(r["ids"]): continue
        for i, x in zip(r["ids"], r["p"]): out[i] = x
    return out
A, B = load(sys.argv[2]), load(sys.argv[3])
def brier(pr, y, n):
    v = np.array(pr[:n], float); v = np.clip(v, 0, None)
    if len(v) != n or v.sum() <= 0: return None
    v = v / v.sum(); t = np.zeros(n); t[y - 1] = 1; return float(((v - t) ** 2).sum())
rows = {q: [] for q in Q}
for i in set(A) & set(B):
    for q in Q:
        y = P[i]["target"][q]; n = len(D["options"][q])
        if y is None or not (1 <= y <= n): continue
        a, b = brier(A[i].get(q, []), y, n), brier(B[i].get(q, []), y, n)
        if a is not None and b is not None: rows[q].append((a, b))
rng = np.random.default_rng(7); allp = []
for q in Q:
    x = np.array(rows[q]); allp += list(x)
    print(f"{q:9s} n {len(x):4d}  persona {x[:, 0].mean():.4f}  record {x[:, 1].mean():.4f}  record better by {(x[:, 0] - x[:, 1]).mean():+.4f}")
x = np.array(allp); d = x[:, 0] - x[:, 1]
bs = [rng.choice(d, len(d)).mean() for _ in range(2000)]
sel = sys.argv[4].split(",") if len(sys.argv) > 4 else Q
xp = np.array([r for q in sel for r in rows[q]]); dp = xp[:, 0] - xp[:, 1]; bp = [rng.choice(dp, len(dp)).mean() for _ in range(2000)]
print(f"PRIMARY ({'+'.join(sel)}) n {len(xp)}  persona {xp[:, 0].mean():.4f}  record {xp[:, 1].mean():.4f}  diff {dp.mean():+.4f}  95% CI [{np.quantile(bp, .025):+.4f}, {np.quantile(bp, .975):+.4f}]  MET {bool(np.quantile(bp, .025) > 0)}")
print(f"ALL      n {len(x)}  persona {x[:, 0].mean():.4f}  record {x[:, 1].mean():.4f}  diff {d.mean():+.4f}  95% CI [{np.quantile(bs, .025):+.4f}, {np.quantile(bs, .975):+.4f}]  relative {d.mean() / x[:, 0].mean() * 100:+.1f}%")
