"""MQG test 27 scorer. Reads the frozen predictions and the 16 run records, applies the plan's rules and writes
mqg_test27_score.json.

Usage: python mqg_test27_score.py --deposit-doi 10.5281/zenodo.X [--outdir mqg_test27_out]
                                  [--predictions mqg_test27_predictions.json]

Observable at slot (cell, N, t): F = sum_k (P+_k - P-_k)/2 e^{-2 pi i k/3}, z = (2/3) F = a e^{i phase}.
Distance between two values z1, z2: D = |z1 - z2| (amplitude units). Phase differences are wrapped to (-pi, pi].
"""
import sys, os, json, hashlib, argparse
import numpy as np

PREDICTIONS_SHA256 = "d579a8e72fd728e03a8675e1e9b727f27d8aff04efef2d98ae480d8a03eee994"
RUNNER_SHA256 = "3768d748e1c889c846e3736d66980f3ec3994942ac6e2a52f3212a33a0122065"
CHIRAL = ("C1", "C2", "C3"); CONTROL = "C0"; ALL = CHIRAL + (CONTROL,); NS = (400, 800)
# thresholds (plan Sec. 5)
SEP = 0.03          # R1, R1L: slot discriminates when D(K, rival) >= SEP
TIE = 0.005         # R1, R1L: tie zone on the difference of distances
NEITHER = 0.02      # R1, R1L: neither rule describes a slot when both distances exceed this
TOL = 0.010         # R3: tolerance on D(exact, K)
PROJ_IN, PROJ_OUT = 0.008, 0.010   # R3 uses slots with D(K, W) <= PROJ_IN; R4 uses slots with D(K, W) >= PROJ_OUT
TIE4 = 0.003        # R4 tie zone
LAG_AMP, LAG_MIN, LAG_TIE, LAG_NEITHER, LAG_OBS_AMP = 0.04, 0.15, 0.03, 0.10, 0.02   # R2
PASS, NEITHER_FRAC, EVAL_FRAC, CONS = 0.8, 0.5, 2/3, 2/3
G0_AMP, G0_TOL = 0.01, 0.02          # control symmetry check
NORM_TOL = 1e-8

wrap = lambda x: float((x + np.pi) % (2*np.pi) - np.pi)
def z_of(a, ph): return a*np.exp(1j*ph)
def harm(Pp, Pm):
    odd = (np.asarray(Pp) - np.asarray(Pm))/2; F = (odd*np.exp(-2j*np.pi*np.arange(3)/3)).sum(-1); return (2/3)*F

def slot_sets(pred):
    """Slot sets, fixed by the predictions alone."""
    S = {"R1": [], "R1L": [], "R3": [], "R4": [], "R2": []}
    for c in ALL:
        for N in NS:
            for j, r in enumerate(pred["cells"][c]["N"][str(N)]["rows"]):
                K, B, L, W = (z_of(r[x]["a"], r[x]["ph"]) for x in "KBLW")
                if c in CHIRAL and abs(K - B) >= SEP: S["R1"].append((c, N, j))
                if c in CHIRAL and abs(K - L) >= SEP: S["R1L"].append((c, N, j))
                if c in CHIRAL and abs(K - W) <= PROJ_IN: S["R3"].append((c, N, j))
                if abs(K - W) >= PROJ_OUT: S["R4"].append((c, N, j))
    for c in CHIRAL:
        r4, r8 = pred["cells"][c]["N"]["400"]["rows"], pred["cells"][c]["N"]["800"]["rows"]
        for j in range(len(r4)):
            dK = wrap(r8[j]["K"]["ph"] - r4[j]["K"]["ph"])
            if min(r4[j]["K"]["a"], r8[j]["K"]["a"]) >= LAG_AMP and abs(dK) >= LAG_MIN: S["R2"].append((c, j))
    return S

def check_record(r, doi, cell, N, sign, pred):
    if r is None: return "missing"
    if r.get("runner_sha256") != RUNNER_SHA256: return "wrong runner"
    if r.get("deposit_doi") != doi: return "wrong DOI"
    if r.get("predictions_sha256") != PREDICTIONS_SHA256: return "wrong predictions"
    if (r.get("cell"), r.get("N"), r.get("sign")) != (cell, N, sign): return "wrong run label"
    if not (r.get("norm_err_max", 1) <= NORM_TOL and r.get("psum_err_max", 1) <= NORM_TOL): return "norm check failed"
    if len(r.get("t", [])) != 71 or abs(r["t"][1] - 0.1) > 1e-12: return "wrong time grid"
    return "valid"

def two_way(slots, dist_pair, labels, tie=TIE, neither=NEITHER):
    """Generic two-rule decision. dist_pair(slot) -> (d1, d2) or None (void)."""
    l1, l2 = labels; rows = []; n1 = n2 = nt = nn = nv = 0
    for s in slots:
        d = dist_pair(s)
        if d is None: rows.append([*map(str, s), "void"]); nv += 1; continue
        d1, d2 = d
        if min(d1, d2) > neither: lab = "neither"; nn += 1
        elif d2 - d1 >= tie: lab = l1; n1 += 1
        elif d1 - d2 >= tie: lab = l2; n2 += 1
        else: lab = "tie"; nt += 1
        rows.append([*map(str, s), round(d1, 5), round(d2, 5), lab])
    n = len(slots) - nv
    if len(slots) == 0 or n < EVAL_FRAC*len(slots): v = "not evaluable"
    elif nn >= NEITHER_FRAC*n: v = f"neither {l1} nor {l2} describes the exact result"
    elif n1 >= PASS*n: v = f"{l1} favoured over {l2}"
    elif n2 >= PASS*n: v = f"{l2} favoured over {l1}"
    else: v = "does not decide"
    return dict(verdict=v, counts={l1: n1, l2: n2, "tie": nt, "neither": nn, "void": nv, "scored": n}, rows=rows)

def consistency(res, cells):
    """When a rule favours one side, each chiral cell holding slots of the rule must have >= 2/3 of its scored slots
    on that side; otherwise the verdict is reported as not consistent across cells."""
    if " favoured over " not in res["verdict"]: return dict(fraction_on_winning_side={}, consistent=None)
    winner = res["verdict"].split()[0]; out = {}
    for c in cells:
        rows = [r for r in res["rows"] if r[0] == c and r[-1] != "void"]
        if rows: out[c] = round(sum(r[-1] == winner for r in rows)/len(rows), 3)
    ok = all(v >= CONS for v in out.values()) if out else None
    return dict(fraction_on_winning_side=out, consistent=ok)

def score(pred, recs, doi):
    S = slot_sets(pred); status = {}; X = {}
    for c in ALL:
        for N in NS:
            st = {sg: check_record(recs.get((c, N, sg)), doi, c, N, sg, pred) for sg in (+1, -1)}
            status[f"{c}_N{N}"] = st
            for j, r in enumerate(pred["cells"][c]["N"][str(N)]["rows"]):
                if st[+1] == "valid" and st[-1] == "valid":
                    i = int(round(r["t"]/0.1)); X[(c, N, j)] = complex(harm(recs[(c, N, +1)]["P"][i], recs[(c, N, -1)]["P"][i]))
    P = lambda c, N, j, k: z_of(pred["cells"][c]["N"][str(N)]["rows"][j][k]["a"], pred["cells"][c]["N"][str(N)]["rows"][j][k]["ph"])
    out = dict(deposit_doi=doi, predictions_sha256=PREDICTIONS_SHA256, runner_sha256=RUNNER_SHA256, run_status=status,
               slot_sets={k: [list(map(str, s)) for s in v] for k, v in S.items()})
    # G0: control symmetry (code check)
    phs = pred["cells"][CONTROL]["N"]["400"]["rows"][0]["K"]["ph"]; g0 = []
    for N in NS:
        for j in range(6):
            x = X.get((CONTROL, N, j))
            if x is None or abs(x) < G0_AMP: continue
            g0.append(min(abs(wrap(np.angle(x) - phs)), abs(wrap(np.angle(x) - phs + np.pi))))
    out["G0"] = dict(max_deviation=round(max(g0), 5) if g0 else None, slots=len(g0),
                     passed=(bool(g0) and max(g0) <= G0_TOL))
    nvalid = sum(v == "valid" for st in status.values() for v in st.values())
    if nvalid == 0:
        out["test_status"] = "VOID: no valid run record (check the deposit DOI and the runner hash); no rule is applied"; return out
    if not out["G0"]["passed"]:
        out["test_status"] = "VOID: control symmetry check G0 failed or not evaluable; no rule is applied"; return out
    out["test_status"] = "scored"
    dp = lambda rival: (lambda s: None if s not in X else (abs(X[s] - P(*s, "K")), abs(X[s] - P(*s, rival))))
    out["R1"] = two_way(S["R1"], dp("B"), ("K", "B")); out["R1"]["consistency"] = consistency(out["R1"], CHIRAL)
    out["R1L"] = two_way(S["R1L"], dp("L"), ("K", "L"))
    # R2: lag, K against Z (no N dependence)
    def lag(s):
        c, j = s; x4, x8 = X.get((c, 400, j)), X.get((c, 800, j))
        if x4 is None or x8 is None or min(abs(x4), abs(x8)) < LAG_OBS_AMP: return None
        d = wrap(np.angle(x8) - np.angle(x4)); dK = wrap(pred["cells"][c]["N"]["800"]["rows"][j]["K"]["ph"] - pred["cells"][c]["N"]["400"]["rows"][j]["K"]["ph"])
        return abs(wrap(d - dK)), abs(d)
    out["R2"] = two_way(S["R2"], lag, ("K", "Z"), tie=LAG_TIE, neither=LAG_NEITHER)
    for row, s in zip(out["R2"]["rows"], S["R2"]):
        c, j = s; x4, x8 = X.get((c, 400, j)), X.get((c, 800, j))
        if x4 is not None and x8 is not None: row.insert(2, round(wrap(np.angle(x8) - np.angle(x4)), 4))
    out["R2"]["consistency"] = consistency(out["R2"], CHIRAL)
    # R3: accuracy of K on projection-valid chiral slots
    rows = []; ok = bad = nv = 0
    for s in S["R3"]:
        if s not in X: rows.append([*map(str, s), "void"]); nv += 1; continue
        d = abs(X[s] - P(*s, "K")); lab = "within" if d <= TOL else "outside"; ok += int(d <= TOL); bad += int(d > TOL)
        rows.append([*map(str, s), round(d, 5), lab])
    n = len(S["R3"]) - nv
    v = ("not evaluable" if n < EVAL_FRAC*len(S["R3"]) else "K CONFIRMED" if bad == 0 else
         "K PARTLY CONFIRMED" if ok >= PASS*n else "K FAILS")
    out["R3"] = dict(verdict=v, counts=dict(within=ok, outside=bad, void=nv, scored=n),
                     max_distance=round(max([r[3] for r in rows if r[-1] != "void"]), 5) if n else None, rows=rows)
    # R4 (secondary): projection, W against K where they separate
    out["R4"] = two_way(S["R4"], lambda s: None if s not in X else (abs(X[s] - P(*s, "W")), abs(X[s] - P(*s, "K"))), ("W", "K"), tie=TIE4)
    # Q (reported): exact minus TWA at every slot
    q = []
    for c in ALL:
        for N in NS:
            for j, r in enumerate(pred["cells"][c]["N"][str(N)]["rows"]):
                if (c, N, j) not in X: continue
                x, w = X[(c, N, j)], P(c, N, j, "W")
                q.append(dict(cell=c, N=N, t=r["t"], a=round(abs(x), 5), phase=round(float(np.angle(x)), 4),
                              da=round(abs(x) - abs(w), 5), dphase=round(wrap(np.angle(x) - np.angle(w)), 4), D=round(abs(x - w), 5),
                              a_se=r["W"]["a_se"], z=round((abs(x) - abs(w))/r["W"]["a_se"], 2)))
    med = {f"{c}_N{N}": round(float(np.median([e["D"] for e in q if e["cell"] == c and e["N"] == N])), 5)
           for c in ALL for N in NS if any(e["cell"] == c and e["N"] == N for e in q)}
    out["Q"] = dict(rows=q, median_D=med, slots_beyond_4se=int(sum(abs(e["z"]) > 4 for e in q)))
    return out

def load_records(d):
    recs = {}
    for c in ALL:
        for N in NS:
            for sg in (+1, -1):
                fn = os.path.join(d, f"{c}_N{N}_{'p' if sg > 0 else 'm'}.json")
                recs[(c, N, sg)] = json.load(open(fn)) if os.path.exists(fn) else None
    return recs

def report(out):
    print("test status:", out["test_status"]); print("G0 control symmetry:", out["G0"])
    for k in ("R1", "R1L", "R2", "R3", "R4"):
        if k in out: print(f"{k}: {out[k]['verdict']}  {out[k]['counts']}" + (f"  consistency {out[k]['consistency']}" if "consistency" in out[k] else ""))
    if "Q" in out: print("Q median D(exact, W):", out["Q"]["median_D"], " slots beyond 4 SE:", out["Q"]["slots_beyond_4se"])

if __name__ == "__main__":
    ap = argparse.ArgumentParser(); ap.add_argument("--deposit-doi", required=True)
    ap.add_argument("--outdir", default="mqg_test27_out"); ap.add_argument("--predictions", default="mqg_test27_predictions.json")
    A = ap.parse_args()
    if hashlib.sha256(open(A.predictions, "rb").read()).hexdigest() != PREDICTIONS_SHA256: sys.exit("refused: predictions SHA-256 differs")
    pred = json.load(open(A.predictions))
    out = score(pred, load_records(os.path.join(A.outdir, "run_records")), A.deposit_doi)
    json.dump(out, open(os.path.join(A.outdir, "mqg_test27_score.json"), "w"), indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o))
    report(out); print("wrote", os.path.join(A.outdir, "mqg_test27_score.json"))
