"""MQG test 27: synthetic-record tests of mqg_test27_score.py. Every branch of every rule is exercised with records
built from the frozen predictions (no exact run is involved). Usage: python mqg_test27_score_tests.py"""
import json, os, sys, numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import mqg_test27_score as S

pred = json.load(open("mqg_test27_predictions.json")); DOI = "10.5281/zenodo.123"
def zp(c, N, j, k):
    r = pred["cells"][c]["N"][str(N)]["rows"][j][k]; return r["a"]*np.exp(1j*r["ph"])

def records(target, drop=(), patch=None):
    """target(c, N, j) -> complex z of the synthetic exact result at slot j."""
    recs = {}
    for c in S.ALL:
        for N in S.NS:
            P = {+1: np.full((71, 3), 1/3), -1: np.full((71, 3), 1/3)}
            for j, r in enumerate(pred["cells"][c]["N"][str(N)]["rows"]):
                z = target(c, N, j); i = int(round(r["t"]/0.1))
                odd = abs(z)*np.cos(np.angle(z) + 2*np.pi*np.arange(3)/3)
                P[+1][i] = 1/3 + odd; P[-1][i] = 1/3 - odd
            for sg in (+1, -1):
                rec = dict(cell=c, N=N, sign=sg, t=[round(0.1*k, 10) for k in range(71)], P=P[sg].tolist(),
                           norm_err_max=1e-13, psum_err_max=1e-13, runner_sha256=S.RUNNER_SHA256,
                           predictions_sha256=S.PREDICTIONS_SHA256, deposit_doi=DOI)
                if patch: patch(rec)
                recs[(c, N, sg)] = None if (c, N, sg) in drop else rec
    return recs

K = lambda c, N, j: zp(c, N, j, "K")
def ctrl(f):            # the control cell always follows K (pinned phase) unless the test says otherwise
    return lambda c, N, j: zp(c, N, j, "K") if c == "C0" else f(c, N, j)
cases = []
def case(name, recs, expect):
    out = S.score(pred, recs, DOI); got = {}
    for k in expect:
        got[k] = out["test_status"] if k == "status" else (out[k]["verdict"] if k in out else None) if k not in ("R1cons", "R2cons") else out[k[:2]]["consistency"]["consistent"]
    ok = all(got[k] == v for k, v in expect.items()); cases.append(ok)
    print(("PASS " if ok else "FAIL ") + name + "  " + "; ".join(f"{k}: {got[k]}" for k in expect))

case("exact equals K", records(K), dict(status="scored", R1="K favoured over B", R1L="K favoured over L", R2="K favoured over Z",
     R3="K CONFIRMED", R4="K favoured over W", R1cons=True))
case("exact equals B (chiral cells)", records(ctrl(lambda c, N, j: zp(c, N, j, "B"))), dict(R1="B favoured over K", R3="K FAILS"))
case("exact equals L (chiral cells)", records(ctrl(lambda c, N, j: zp(c, N, j, "L"))), dict(R1L="L favoured over K"))
case("exact equals W (all cells)", records(lambda c, N, j: zp(c, N, j, "W") if c != "C0" else abs(zp(c, N, j, "W"))*np.exp(1j*np.angle(zp(c, N, j, "K")))),
     dict(R1="K favoured over B", R2="K favoured over Z", R3="K CONFIRMED", R4="W favoured over K"))
case("no lag: N = 800 copies N = 400", records(ctrl(lambda c, N, j: zp(c, 400, j, "K"))), dict(R2="Z favoured over K"))
case("half lag", records(ctrl(lambda c, N, j: zp(c, N, j, "K") if N == 400 else abs(zp(c, N, j, "K"))*np.exp(1j*(np.angle(zp(c, 400, j, "K")) + 0.5*S.wrap(np.angle(zp(c, 800, j, "K")) - np.angle(zp(c, 400, j, "K"))))))),
     dict(R2="neither K nor Z describes the exact result"))
case("double lag", records(ctrl(lambda c, N, j: zp(c, N, j, "K") if N == 400 else abs(zp(c, N, j, "K"))*np.exp(1j*(np.angle(zp(c, 400, j, "K")) + 2.0*S.wrap(np.angle(zp(c, 800, j, "K")) - np.angle(zp(c, 400, j, "K"))))))),
     dict(R2="neither K nor Z describes the exact result"))
case("K rotated by 1 rad", records(ctrl(lambda c, N, j: zp(c, N, j, "K")*np.exp(1j))), dict(R1="neither K nor B describes the exact result", R3="K FAILS"))
case("midpoint of K and B", records(ctrl(lambda c, N, j: (zp(c, N, j, "K") + zp(c, N, j, "B"))/2)), dict(R1="neither K nor B describes the exact result"))
case("K in C2, B in C3", records(ctrl(lambda c, N, j: zp(c, N, j, "B") if c == "C3" else zp(c, N, j, "K"))), dict(R1="does not decide"))
case("K in C2 and C3 at N = 800, B in C3 at N = 400", records(ctrl(lambda c, N, j: zp(c, N, j, "B") if (c, N) == ("C3", 400) else zp(c, N, j, "K"))),
     dict(R1="does not decide"))
offs = {("C1", 400, 0), ("C1", 400, 1), ("C2", 800, 2)}
case("K off by 0.012 at 3 of 30 R3 slots", records(ctrl(lambda c, N, j: zp(c, N, j, "K") + (0.012 if (c, N, j) in offs else 0))), dict(R3="K PARTLY CONFIRMED"))
offs2 = {(c, N, j) for c in ("C1",) for N in (400, 800) for j in range(6)}
case("K off by 0.012 at 12 of 30 R3 slots", records(ctrl(lambda c, N, j: zp(c, N, j, "K") + (0.012 if (c, N, j) in offs2 else 0))), dict(R3="K FAILS"))
case("R4 ties: exact at the midpoint of K and W", records(lambda c, N, j: (zp(c, N, j, "K") + zp(c, N, j, "W"))/2 if (c != "C0" or abs(zp(c, N, j, "K") - zp(c, N, j, "W")) < 0.03) else zp(c, N, j, "K")),
     dict(status="scored", R4="does not decide"))
case("R2: no lag in C3 only (K favoured, not consistent across cells)", records(ctrl(lambda c, N, j: zp(c, 400, j, "K") if c == "C3" else zp(c, N, j, "K"))),
     dict(R2="K favoured over Z", R2cons=False))
case("R2 mixed: lag in C1, no lag in C2 and C3", records(ctrl(lambda c, N, j: zp(c, 400, j, "K") if c in ("C2", "C3") else zp(c, N, j, "K"))), dict(R2="does not decide"))
# void and record checks
drop1 = {(c, 800, sg) for c in ("C2",) for sg in (1, -1)}
case("C2 N = 800 missing (R1 still evaluable)", records(K, drop=drop1), dict(status="scored", R1="K favoured over B"))
drop2 = {(c, 800, sg) for c in ("C2", "C3") for sg in (1, -1)}
case("C2 and C3 N = 800 missing (R2 keeps 6 of 9 slots)", records(K, drop=drop2), dict(R1="not evaluable", R2="K favoured over Z"))
drop3 = {(c, 800, sg) for c in ("C1", "C2") for sg in (1, -1)}
case("C1 and C2 N = 800 missing", records(K, drop=drop3), dict(R2="not evaluable"))
def badrun(rec):
    if rec["cell"] == "C3" and rec["N"] == 800: rec["runner_sha256"] = "0"*64
case("wrong runner hash on C3 N = 800", records(K, patch=badrun), dict(R1="K favoured over B"))
def baddoi(rec): rec["deposit_doi"] = "10.5281/zenodo.999"
case("wrong DOI on every record", records(K, patch=baddoi), dict(status="VOID: no valid run record (check the deposit DOI and the runner hash); no rule is applied"))
def badnorm(rec):
    if rec["cell"] in ("C1", "C2", "C3") and rec["N"] == 400: rec["norm_err_max"] = 1e-6
case("norm failure in all chiral N = 400 runs", records(K, patch=badnorm), dict(R1="not evaluable", R3="not evaluable", R2="not evaluable"))
case("control phase off by 0.5 rad", records(lambda c, N, j: zp(c, N, j, "K")*(np.exp(0.5j) if c == "C0" else 1)),
     dict(status="VOID: control symmetry check G0 failed or not evaluable; no rule is applied"))
case("control phase flipped by pi (allowed)", records(lambda c, N, j: -zp(c, N, j, "K") if c == "C0" else zp(c, N, j, "K")), dict(status="scored"))
print(f"{sum(cases)} of {len(cases)} cases pass")
print("ALL SCORE TESTS PASS" if all(cases) else "SOME SCORE TESTS FAIL")
