"""Registered scorer (protocol-national-2025-men.json): men's 2025 life expectancy from six national
statistics offices against the frozen forecast gain added to each office's own 2005 value, with the
frozen 80% intervals and the blocks baseline's intervals moved by the same amount.
Usage: score-national-2025-men.py (run from experiment/lives)"""
import json, hashlib, subprocess, sys
P = json.load(open("protocol-national-2025-men.json"))
for f, h in P["frozen_sha256"].items():
    assert hashlib.sha256(open(f, "rb").read()).hexdigest() == h, f
F = {r["country"]: r["male"] for r in json.load(open("forecast-e0-men-v3-2005.json"))["rows"]}
N05 = json.load(open("national-e0-men-2005.json"))["values"]
N25 = json.loads(subprocess.run([sys.executable, "national_e0_men.py", "2025"], capture_output=True, text=True, check=True).stdout)["values"]
score = lambda lo, hi, x: (hi - lo) + 10 * max(0, lo - x) + 10 * max(0, x - hi)  # interval score for 80% intervals
rows, errs, cov, bcov, iss, biss = {}, [], 0, 0, [], []
for c in P["countries"]:
    m = F[c]; shift = N05[c] - m["atOrigin"]
    pred, lo, hi = m["forecast"] + shift, m["lo80"] + shift, m["hi80"] + shift
    blo, bhi = m["baselineBlocks"]["lo80"] + shift, m["baselineBlocks"]["hi80"] + shift
    x = N25[c]; e = pred - x; errs.append(e)
    cov += lo <= x <= hi; bcov += blo <= x <= bhi; iss.append(score(lo, hi, x)); biss.append(score(blo, bhi, x))
    rows[c] = {"e2005": N05[c], "predicted": round(pred, 2), "lo80": round(lo, 2), "hi80": round(hi, 2), "e2025": x, "error": round(e, 2),
               "baseline_lo80": round(blo, 2), "baseline_hi80": round(bhi, 2)}
n = len(errs); mae = sum(abs(e) for e in errs) / n; ms = sum(errs) / n
pr, iv, gp = P["primary"], P["intervals"], P["gap_bias"]
res = {"countries": rows,
       "male": {"n": n, "mae": round(mae, 3), "meanSigned": round(ms, 3), "met": mae <= pr["bar_years"], "stretch": mae <= pr["stretch_years"]},
       "intervals": {"inside": int(cov), "coverage80": round(cov / n, 3), "intervalScore": round(sum(iss) / n, 3),
                     "baseline": {"inside": int(bcov), "coverage80": round(bcov / n, 3), "intervalScore": round(sum(biss) / n, 3)}},
       "gap_bias": {"meanSigned": round(ms, 3), "met": abs(ms) <= gp["abs_mean_signed_at_most"]}}
res["intervals"]["met"] = cov >= iv["inside_at_least"] and sum(iss) < sum(biss)
res["primary_met"] = res["male"]["met"]
json.dump(res, open("results-national-2025-men.json", "w"), indent=1)
print(json.dumps({k: res[k] for k in ("male", "intervals", "gap_bias")}), "primary_met", res["primary_met"])
