"""Scores voiced birth answers the way voiced-fertility.ts does: per age group (18-22, 23-27, 28-32, 33-37,
38-42, 43-45) the mean answered probability; TFR 18-45 is the sum over single ages of the group mean; the
mean age at childbearing is weighted the same way; both against the UK 2019 tables (uk2019.json).
Consistent if |TFR - real| <= 0.20 and |mean age - real| <= 1.0.

Usage: score_voice_level.py <answers.jsonl with age and p> [out.json]
"""
import sys, json, os, numpy as np
uk = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "uk2019.json")))
asfr = lambda a: uk["asfr"].get(str(a), 0)
G = [(18, 22), (23, 27), (28, 32), (33, 37), (38, 42), (43, 45)]
rows = [json.loads(l) for l in open(sys.argv[1])]
ages = range(18, 46)
rt = sum(asfr(a) for a in ages); rm = sum((a + 0.5) * asfr(a) for a in ages) / rt
groups = []
for lo, hi in G:
    ps = np.array([r["p"] for r in rows if lo <= r["age"] <= hi])
    groups.append({"group": f"{lo}-{hi}", "answered": int(len(ps)), "mean": round(float(ps.mean()), 4), "sd": round(float(ps.std(ddof=1)), 4),
                   "real": round(float(np.mean([asfr(a) for a in range(lo, hi + 1)])), 4)})
mean_at = lambda a: next(g["mean"] for (lo, hi), g in zip(G, groups) if lo <= a <= hi)
tfr = sum(mean_at(a) for a in ages); mac = sum((a + 0.5) * mean_at(a) for a in ages) / tfr
res = {"real": {"tfr18to45": round(rt, 3), "meanAgeAtBirth": round(rm, 2)}, "voiced": {"tfr": round(tfr, 3), "meanAgeAtBirth": round(mac, 2), "groups": groups},
       "decision": {"tfrWithin020": abs(tfr - rt) <= 0.2, "macWithin1": abs(mac - rm) <= 1.0, "consistent": abs(tfr - rt) <= 0.2 and abs(mac - rm) <= 1.0}}
print(json.dumps(res, indent=1))
if len(sys.argv) > 2: json.dump(res, open(sys.argv[2], "w"), indent=1)
