#!/usr/bin/env python3
"""MQG test 30: frozen scoring rules (2026-12-02; rule C reported only, edge rule in the groups, 2026-12-03). Reads the run records and the saved running means of D_m
(series/<run_id>.npz) written by mqg_test30_runner.py and the frozen predictions (mqg_test30_predictions.json, checked by
MD5), and applies the decision rules of MQG_TEST_30_PUBLIC_PLAN.

Estimator. In the window of a slot, in each row, a rank is (as in tests 24, 9T and 28)
  present if its running mean (width 30) stays at or above 0.05 over an interval of length at least 10 inside the window,
  absent if its running mean stays below 0.05 throughout the window, brief otherwise;
its peak time is the centre of the largest running mean in the window. Over the five rows a slot is present if present in all
five, absent if absent in all five, not reached if a window is not covered, otherwise partly. Its peak time t_m is the MEDIAN of
the five row peak times (test 28 used the mean). It is consistent if at least 4 of the 5 row peak times lie within CONS = 5.0
of t_m.
Timing comparison of rule Hx with a rival Y (Y = Ha with prediction t_Pa, or Y = L with t_L) over a frozen slot group:
  a slot qualifies if it is present and consistent; partly, brief, absent or inconsistent slots count for neither side.
  In a qualifying slot, dX = |t_m - t_Px| and dY = |t_m - t_Y|. The slot is described by neither if min(dX, dY) > NEITHER = 5.0;
  otherwise it is nearer Hx if dY - dX >= TIE = 2.0, nearer Y if dX - dY >= TIE, and a tie in between.
  With n qualifying slots (n counts every qualifying slot, including those described by neither): fewer than NMIN = 5 (T1)
  or 3 (T2): the rule does not decide. Otherwise, if at least half are
  described by neither: neither Hx nor Y describes the peak times. Otherwise Hx is favoured over Y if at least ceil(0.8 n) are
  nearer Hx and at most 1 nearer Y; Y is favoured over Hx likewise; else the rule does not decide.
  Reported with it: mean dX, mean dY and the paired mean of dY - dX with its standard error over the qualifying slots.
Primary rule T1: Hx against Ha over group TX.          Secondary rule T2: Hx against L over group TL.
Secondary rule V (Hx against Lin): in CURV (Hx lit, Lin dark) present is Hx's way and absent Lin's way; in CURV_R the reverse.
  Over the n slots of CURV and CURV_R: Hx favoured over Lin if at least ceil(0.8 n) go Hx's way and at most 1 Lin's way; Lin
  favoured likewise; otherwise neither. Partly and brief slots go neither way.
Reported only (C): the status of every CX1 slot (Hx lit, C dark) and CX2 slot (Hx dark, C lit), with C's call, band and
  mismatch. No verdict.
Secondary rule D: over SD (Hx, Ha and Lin dark), holds if at least ceil(0.8 n) are absent.
If any slot of a rule's group is not reached, that rule does not decide.
Reported only: height of every slot against Hx and Ha (agreement factor 1.25 as in test 28), and the row peak times.
Void if any row was written by another runner, solver, moments module or development runner, used NumPy other than 2.4.6, is a
smoke row, has another seed or state, if the rows name more than one deposit DOI, or if the predictions file is not the frozen
one. Incomplete if there are not five rows: no rule is scored, and the rows read are reported.
Usage: python -I mqg_test30_score.py <results folder mqg_test30> <mqg_test30_predictions.json>
       python -I mqg_test30_score.py --selftest <mqg_test30_predictions.json>
"""
import hashlib, json, math, sys, tempfile
from pathlib import Path
import numpy as np

THRESHOLD, PERSIST, FRAC, FACTOR = 0.05, 10.0, 0.8, 1.25
CONS, NEITHER, TIE = 5.0, 5.0, 2.0
NMIN = {'T1': 5, 'T2': 3}
PRED_MD5 = '862a21f4c44952afa744012904522f84'
RUNNER_SHA256 = '91572c16c21798b8234e53a742ad9a3907437a7dc3b40406fd11844a0e950263'
SOLVER_SHA256 = 'cb13dd79a8fc74be6a1a89799587f1362c4c45a96f27e67be821b636a0dc96d0'
MOMENTS_SHA256 = 'cf9903c9ddb12b47b7bf991b0e72beaf60a9fb776db61bb47169e39371c40984'
DEV_SHA256 = '86544c1368c4828256948b8b2ceeca6288d64f56653a36e7fb6f8df69a49ae8f'
SEEDS = {f'MQG30-{i:02d}': 20273000 + i for i in range(1, 6)}
STATE = dict(theta=0.15, mu=3.0, N=1280)


def load_predictions(path, check=True):
    raw = Path(path).read_bytes()
    if check and hashlib.md5(raw).hexdigest() != PRED_MD5:
        raise SystemExit(f'void: {path} is not the frozen predictions file (MD5 {hashlib.md5(raw).hexdigest()}, frozen {PRED_MD5})')
    P = json.loads(raw)
    slots = {(s['m'], s['X']): s for s in P['slots']}
    groups = {g: [k for k, s in slots.items() if g in s['groups']] for g in ('TX', 'TL', 'CURV', 'CURV_R', 'CX1', 'CX2', 'SD')}
    return P, slots, groups


def window(c, r, lo, hi):
    sel = (c >= lo) & (c <= hi)
    cc, rr = c[sel], r[sel]
    p = int(round(PERSIST / (c[1] - c[0])))
    if len(rr) < p + 1 or c[-1] < hi or c[0] > lo:
        return dict(status='not reached', height=float('nan'), t_peak=float('nan'))
    i = int(np.argmax(rr)); h, t = float(rr[i]), float(cc[i])
    ok = rr >= THRESHOLD
    pers = any(ok[j:j + p + 1].all() for j in range(len(ok) - p))
    return dict(status='present' if pers else ('absent' if h < THRESHOLD else 'brief'), height=h, t_peak=t)


def summarize(ws):
    st = [w['status'] for w in ws]
    status = next((v for v in ('present', 'absent', 'not reached') if all(s == v for s in st)), 'partly')
    tp = np.array([w['t_peak'] for w in ws])
    tm = float(np.median(tp))
    consistent = bool(np.sum(np.abs(tp - tm) <= CONS) >= 4) if status != 'not reached' else False
    return dict(status=status, statuses=st, height=float(np.mean([w['height'] for w in ws])), t_med=tm,
                consistent=consistent, heights=[w['height'] for w in ws], t_peaks=tp.tolist())


def check_records(recs):
    bad = []
    for r in recs:
        why = [n for n, ok in (('runner', r.get('runner_sha256') == RUNNER_SHA256), ('solver', r.get('solver_sha256') == SOLVER_SHA256),
                               ('moments module', r.get('moments_sha256') == MOMENTS_SHA256),
                               ('development runner', r.get('dev_runner_sha256') == DEV_SHA256), ('NumPy', r.get('numpy_version') == '2.4.6'),
                               ('smoke row', r.get('smoke') is False), ('seed', SEEDS.get(r.get('run_id')) == r.get('seed')),
                               ('state', all(r.get(k) == v for k, v in STATE.items()))) if not ok]
        if why:
            bad.append((r.get('run_id'), why))
    dois = {r.get('deposit_doi') for r in recs}
    if len(dois) > 1:
        bad.append(('all rows', [f'more than one deposit DOI: {sorted(map(str, dois))}']))
    return bad


def timing_rule(name, S, slots, keys, ykey, ylabel):
    """Timing comparison of Hx with rival Y over the slots keys; returns (verdict text, details)."""
    nr = [k for k in keys if S[k]['status'] == 'not reached']
    if nr:
        return f'windows not reached at {nr}: the rule does not decide', {}
    det, q = [], []
    for k in keys:
        s, e = slots[k], S[k]
        if e['status'] != 'present' or not e['consistent']:
            det.append(dict(slot=list(k), qualifies=False, status=e['status'], consistent=e['consistent'])); continue
        dX, dY = abs(e['t_med'] - s['t_Px']), abs(e['t_med'] - s[ykey])
        side = 'neither' if min(dX, dY) > NEITHER else ('Hx' if dY - dX >= TIE else (ylabel if dX - dY >= TIE else 'tie'))
        q.append((dX, dY, side))
        det.append(dict(slot=list(k), qualifies=True, t_med=e['t_med'], t_Px=s['t_Px'], t_Y=s[ykey], dX=dX, dY=dY, side=side))
    n = len(q)
    info = dict(n_group=len(keys), n_qualifying=n, slots=det)
    if n:
        diff = np.array([b - a for a, b, _ in q])
        info.update(mean_dX=float(np.mean([a for a, _, _ in q])), mean_dY=float(np.mean([b for _, b, _ in q])),
                    paired_mean=float(diff.mean()), paired_se=float(diff.std(ddof=1) / math.sqrt(n)) if n > 1 else float('nan'))
    nX, nY, nN, nT = (sum(t[2] == v for t in q) for v in ('Hx', ylabel, 'neither', 'tie'))
    info.update(nearer_Hx=nX, nearer_Y=nY, neither=nN, ties=nT)
    tag = f'{n} of {len(keys)} slots qualify; nearer Hx {nX}, nearer {ylabel} {nY}, ties {nT}, described by neither {nN}'
    if n < NMIN[name]:
        return f'{tag}: fewer than {NMIN[name]} qualifying slots, the rule does not decide', info
    need = math.ceil(FRAC * n)
    if nN >= n / 2:
        return f'{tag}: neither Hx nor {ylabel} describes the peak times', info
    if nX >= need and nY <= 1:
        return f'{tag}: Hx favoured over {ylabel}', info
    if nY >= need and nX <= 1:
        return f'{tag}: {ylabel} favoured over Hx', info
    return f'{tag}: does not decide (needs {need} of {n} with at most 1 against)', info


def ways_rule(S, keys_hx_present, keys_hx_absent, rival, nmin=1):
    keys = keys_hx_present + keys_hx_absent
    nr = [k for k in keys if S[k]['status'] == 'not reached']
    if nr:
        return f'windows not reached at {nr}: the rule does not decide', {}
    hx = sum(S[k]['status'] == 'present' for k in keys_hx_present) + sum(S[k]['status'] == 'absent' for k in keys_hx_absent)
    rv = sum(S[k]['status'] == 'absent' for k in keys_hx_present) + sum(S[k]['status'] == 'present' for k in keys_hx_absent)
    n = len(keys); info = dict(n=n, hx_way=hx, rival_way=rv)
    tag = f"{hx} of {n} slots go Hx's way, {rv} go {rival}'s way"
    if n < nmin:
        return f'{tag}: fewer than {nmin} slots, the rule does not decide', info
    need = math.ceil(FRAC * n)
    if hx >= need and rv <= 1:
        return f'{tag}: Hx favoured over {rival}', info
    if rv >= need and hx <= 1:
        return f'{tag}: {rival} favoured over Hx', info
    return f'{tag}: neither', info


def main(res, pred_path, check_pred=True):
    P, slots, G = load_predictions(pred_path, check_pred)
    res = Path(res)
    recs = [json.loads(p.read_text()) for p in sorted((res / 'run_records').glob('MQG30-*.json'))]
    print(f'MQG test 30 scoring: {len(recs)} rows read')
    out = dict(rows=len(recs))
    bad = check_records(recs)
    if bad:
        out['verdict'] = f'void: rows fail the record checks {bad}'; print(out['verdict']); return out
    if len(recs) != 5:
        out['rows_read'] = [r.get('run_id') for r in recs]
        out['verdict'] = f'incomplete: {len(recs)} rows, the plan needs 5; no rule is scored; rows read {out["rows_read"]}'; print(out['verdict']); return out
    ser = [np.load(res / r['series_file']) for r in recs]
    S = {k: summarize([window(z['centers'], z[f'D{k[0]}'], *s['window']) for z in ser]) for k, s in slots.items()}
    tK = P['spectral_tK']
    print('The slots (t_L = X t_K/m; times in units of t_K):')
    for k, s in slots.items():
        e = S[k]
        print(f"  ({k[0]},{k[1]:2d}) {e['status']:11s} {'cons' if e['consistent'] else '    '} height {e['height']:+.4f} t_med {e['t_med'] / tK:.4f} | "
              f"Hx {s['Hx']:+.4f} ({s['call_x']}) at {s['t_Px'] / tK:.4f}  Ha {s['Ha']:+.4f} at {s['t_Pa'] / tK:.4f}  Lin {s['call_lin']}  "
              f"C {s['call_C']}  L at {s['t_L'] / tK:.4f}  {' '.join(s['groups'])}")
    T1, i1 = timing_rule('T1', S, slots, G['TX'], 't_Pa', 'Ha')
    T2, i2 = timing_rule('T2', S, slots, G['TL'], 't_L', 'L')
    V, iv = ways_rule(S, G['CURV'], G['CURV_R'], 'Lin')
    ic = {f'{k[0]} {k[1]}': dict(group=g, status=S[k]['status'], consistent=S[k]['consistent'], call_C=slots[k]['call_C'],
                                 C_band=slots[k]['C_band'], C_mismatch=slots[k]['C_mismatch']) for g in ('CX1', 'CX2') for k in G[g]}
    C = 'reported only: ' + ('; '.join(f"({k}) {v['group']} {v['status']}" for k, v in ic.items()) if ic else 'no slots')
    if any(S[k]['status'] == 'not reached' for k in G['SD']):
        D = 'windows not reached: the rule does not decide'
    else:
        nD = sum(S[k]['status'] == 'absent' for k in G['SD']); need = math.ceil(FRAC * len(G['SD']))
        D = f"{nD} of the {len(G['SD'])} shared dark slots absent: " + ('holds' if nD >= need else 'fails') + f' (pass mark {need})'
    for lab, v in (('Primary rule T1 (timing, Hx against Ha)', T1), ('Secondary rule T2 (timing, Hx against L)', T2),
                   ('Secondary rule V (Hx against Lin)', V), ('Rival C', C), ('Secondary rule D', D)):
        print(f'{lab}: {v}')
    for lab, info in (('T1', i1), ('T2', i2)):
        if info.get('n_qualifying'):
            print(f"  {lab}: mean dX {info['mean_dX']:.2f}, mean dY {info['mean_dY']:.2f}, paired mean dY - dX {info['paired_mean']:.2f} "
                  f"(SE {info['paired_se']:.2f})")
    within = lambda h, H: bool(h == h and h > 0 and H > 0 and 1 / FACTOR <= h / H <= FACTOR)
    lit = [k for k, s in slots.items() if s['call_x'] == 'lit']
    hrep = dict(Hx=sum(within(S[k]['height'], slots[k]['Hx']) for k in lit), Ha=sum(within(S[k]['height'], slots[k]['Ha']) for k in lit), n=len(lit))
    print(f"Reported only: heights of the {len(lit)} Hx-lit slots within a factor 1.25 of Hx in {hrep['Hx']}, of Ha in {hrep['Ha']}")
    out.update(primary_T1=T1, secondary_T2=T2, secondary_V=V, reported_C=C, secondary_D=D, T1_detail=i1, T2_detail=i2,
               V_detail=iv, C_detail=ic, heights_reported=hrep, slots={f'{k[0]} {k[1]}': v for k, v in S.items()})
    return out


def selftest(pred_path):
    """Synthetic rows for every branch of every rule, censoring, inconsistency, void and incomplete cases."""
    P, slots, G = load_predictions(pred_path)
    print('groups:', {g: len(v) for g, v in G.items()})
    rec0 = dict(runner_sha256=RUNNER_SHA256, solver_sha256=SOLVER_SHA256, moments_sha256=MOMENTS_SHA256, dev_runner_sha256=DEV_SHA256,
                numpy_version='2.4.6', smoke=False, deposit_doi='10.5281/zenodo.TEST', **STATE)
    tmax_full = P['T_max'] - 15.0
    c = np.round(np.arange(15.0, tmax_full + 0.25, 0.5), 10)

    def make(tmp, spec, tmax=tmax_full, nrows=5, edit=None, jitter=None):
        """spec: {slot: (height, time)}; jitter: {slot: list of 5 time offsets}."""
        d = Path(tmp); (d / 'run_records').mkdir(parents=True); (d / 'series').mkdir()
        cc = c[c <= tmax]
        for i in range(1, nrows + 1):
            rid = f'MQG30-{i:02d}'; ser = {f'D{m}': np.zeros_like(cc) for m in range(1, 8)}
            for k, (h, t) in spec.items():
                lo, hi = slots[k]['window']; t0 = t + (jitter[k][i - 1] if jitter and k in jitter else 0.0)
                t0 = min(max(t0, lo + 0.5), hi - 0.5)
                bump = 0.06 + (h - 0.06) * np.exp(-0.5 * ((cc - t0) / 6.0) ** 2) if h > 0.06 else h * np.exp(-0.5 * ((cc - t0) / 6.0) ** 2)
                bump[(cc < lo) | (cc >= hi)] = 0.0       # a pedestal of 0.06 keeps a lit slot present even when it peaks at an edge
                ser[f'D{k[0]}'] = np.maximum(ser[f'D{k[0]}'], bump)
            np.savez(d / 'series' / f'{rid}.npz', centers=cc, **ser)
            r = dict(rec0, run_id=rid, seed=SEEDS[rid], series_file=f'series/{rid}.npz')
            if edit and i == 1: r.update(edit)
            (d / 'run_records' / f'{rid}.json').write_text(json.dumps(r))
        return main(d, pred_path)

    lit = lambda key: {k: (max(slots[k]['Hx'], 0.12), slots[k][key]) for k, s in slots.items() if s['call_x'] == 'lit'}
    asX = lit('t_Px')
    res = []
    def case(name, cond):
        res.append((name, bool(cond))); print(('PASS ' if cond else 'FAIL ') + name)
    def run(name, spec, cond, **kw):
        with tempfile.TemporaryDirectory() as t:
            o = make(t, spec, **kw); case(name, cond(o))
    run('all at t_Px: Hx over Ha, Hx over L, Hx over Lin, D holds', asX, lambda o: o['primary_T1'].endswith('Hx favoured over Ha')
        and o['secondary_T2'].endswith('Hx favoured over L') and o['secondary_V'].endswith('Hx favoured over Lin') and ': holds' in o['secondary_D'])
    run('all at t_Pa: Ha over Hx', lit('t_Pa'), lambda o: o['primary_T1'].endswith('Ha favoured over Hx'))
    run('all at t_L: L over Hx', lit('t_L'), lambda o: o['secondary_T2'].endswith('L favoured over Hx'))
    mid = {k: (h, (slots[k]['t_Px'] + slots[k]['t_Pa']) / 2) for k, (h, _) in asX.items()}
    run('midway between t_Px and t_Pa: T1 ties or neither, never a winner', mid,
        lambda o: 'favoured' not in o['primary_T1'])
    far = {k: (h, slots[k]['t_Px'] + (12.0 if slots[k]['t_Pa'] < slots[k]['t_Px'] else -12.0)) for k, (h, _) in asX.items()}
    run('12 beyond t_Px on the far side from t_Pa: neither describes', far, lambda o: 'neither Hx nor Ha describes' in o['primary_T1'])
    half = dict(asX); flip = G['TX'][:len(G['TX']) // 2]
    half.update({k: (asX[k][0], slots[k]['t_Pa']) for k in flip})
    run('half at t_Pa: T1 does not decide', half, lambda o: o['primary_T1'].split(': ')[-1].startswith('does not decide'))
    jit = {k: [0.0, 0.0, 0.0, 9.0, -9.0] for k in G['TX']}
    run('two rows jump by 9 in every TX slot: inconsistent, T1 does not decide', asX, lambda o: 'fewer than' in o['primary_T1'], jitter=jit)
    jit1 = {k: [0.0, 0.0, 0.0, 0.0, 12.0] for k in G['TX']}
    run('one row jumps by 12: median unaffected, Hx over Ha', asX, lambda o: o['primary_T1'].endswith('Hx favoured over Ha'), jitter=jit1)
    run('nothing returns: Lin over Hx if CURV dominates, D holds, T1 does not decide', {},
        lambda o: 'fewer than' in o['primary_T1'] and (o['secondary_V'].endswith('Lin favoured over Hx') or len(G['CURV_R']) > 0))
    nc = {k: v for k, v in asX.items() if k not in G['CURV'][:len(G['CURV']) // 2]}
    run('half of CURV absent: V neither', nc, lambda o: o['secondary_V'].endswith('neither'))
    cs = {k: v for k, v in asX.items() if k not in G['CX1']}; cs.update({k: (0.12, slots[k]['t_L']) for k in G['CX2']})
    run('C slots go C\'s way: reported only, no verdict on C', cs, lambda o: o['reported_C'].startswith('reported only')
        and 'favoured' not in o['reported_C'] and all(v['status'] == 'absent' for v in o['C_detail'].values() if v['group'] == 'CX1'))
    sd = dict(asX); sd.update({k: (0.12, slots[k]['t_L']) for k in G['SD']})
    run('shared dark slots present: D fails', sd, lambda o: 'fails' in o['secondary_D'])
    run('window not reached: T1 and T2 do not decide', asX, lambda o: 'not reached' in o['primary_T1'] or 'not reached' in o['secondary_T2'],
        tmax=P['spectral_tK'] * 2.0)
    for ed, label in ((dict(numpy_version='2.1.3'), 'NumPy'), (dict(smoke=True), 'smoke row'), (dict(seed=1), 'seed'),
                      (dict(runner_sha256='x'), 'runner'), (dict(theta=0.40), 'state'), (dict(deposit_doi='other'), 'deposit DOI')):
        run(f'void on {label}', asX, lambda o: o.get('verdict', '').startswith('void'), edit=ed)
    run('incomplete with 4 rows: no rule scored, rows reported', asX, lambda o: o.get('verdict', '').startswith('incomplete')
        and len(o.get('rows_read', [])) == 4 and 'primary_T1' not in o, nrows=4)
    def one(tm, tpa=120.0):
        S = {(1, 1): dict(status='present', consistent=True, t_med=tm)}
        return timing_rule('T2', S, {(1, 1): {'t_Px': 100.0, 't_Pa': tpa}}, [(1, 1)], 't_Pa', 'Ha')[1]['slots'][0]['side']
    case('slot sides: tie zone 2 and neither tolerance 5', one(100.0) == 'Hx' and one(104.9) == 'Hx' and one(110.0) == 'neither'
         and one(115.1) == 'Ha' and one(94.9) == 'neither' and one(125.1) == 'neither' and one(95.0) == 'Hx'
         and one(103.4, 105.0) == 'tie' and one(101.4, 105.0) == 'Hx' and one(104.1, 105.0) == 'Ha')
    try:
        tmp = Path(tempfile.mkdtemp()) / 'p.json'; tmp.write_bytes(Path(pred_path).read_bytes() + b' ')
        load_predictions(tmp); case('altered predictions file is refused', False)
    except SystemExit as e:
        case('altered predictions file is refused', str(e).startswith('void'))
    print('SELFTEST:', 'ALL PASS' if all(r[1] for r in res) else 'FAILURES', f'({sum(r[1] for r in res)}/{len(res)})')
    return all(r[1] for r in res)


if __name__ == '__main__':
    if sys.argv[1] == '--selftest':
        sys.exit(0 if selftest(sys.argv[2]) else 1)
    res = sys.argv[1]
    o = main(res, sys.argv[2])
    Path(res, 'MQG_TEST_30_SCORE.json').write_text(json.dumps(o, indent=2, default=lambda x: x.item()), encoding='utf-8')
