#!/usr/bin/env python3
"""MQG test 9T: frozen scoring rules (2026-11-30). Reads the run records and the saved running means of D_m
(series/<run_id>.npz) written by mqg_test9T_runner.py, and applies the decision rules of MQG_TEST_9T_PUBLIC_PLAN.

Estimator (that of test 24, mqg_test24_score.py, doi:10.5281/zenodo.24520167, unchanged). In the window of a slot a rank is
  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 height is the largest running mean in the window and its peak time the centre where it occurs. Over the five rows: present
if present in all five, absent if absent in all five, not reached if a window is not covered, otherwise partly; height and
peak time are means over the five rows.
Primary rule B1: the 3 slots that P and K both call lit (group SL), P and K together against A (odd ranks absent).
Primary rule B2: the 8 slots that P and K both call dark and Q calls lit (group BQ), P and K together against Q.
Secondary: D (all 12 slots that P and K call dark), H (heights of P on its lit slots; factor 1.3, rank 7 factor 1.5),
  T (timing of P against L, nominal hour), replicate consistency of peak times. Slots that P or K calls tie are reported only.
Usage: python mqg_test9T_score.py <results dir holding run_records/ and series/>     Self-test: python mqg_test9T_score.py --selftest
"""
import sys, json, math, tempfile
from pathlib import Path
import numpy as np

THRESHOLD, PERSIST = 0.05, 10.0
RUNNER_SHA256 = '927d88fad3c4c45c6045cc156a01a027d8027f2ca26dd560b55de0152cae4d6f'
SOLVER_SHA256 = 'cb13dd79a8fc74be6a1a89799587f1362c4c45a96f27e67be821b636a0dc96d0'
MOMENTS_SHA256 = 'cf9903c9ddb12b47b7bf991b0e72beaf60a9fb776db61bb47169e39371c40984'
DEV_SHA256 = '86544c1368c4828256948b8b2ceeca6288d64f56653a36e7fb6f8df69a49ae8f'
T_K = 2579.48                                   # layer time t_K = pi/|e_KK| from the exact spectrum
SEEDS = {f'MQG9T-{i:02d}': 20272900 + i for i in range(1, 6)}
SLOTS = {
    (1, 2): dict(win=(3869.22, 6448.7), P=0.00056, tP=6096.0, callP='dark', callK='dark', Q=0.17733, callQ='lit', tL=5158.96, group='SD', BQ=True),
    (3, 5): dict(win=(3869.22, 4729.05), P=0.12194, tP=4338.5, callP='lit', callK='lit', Q=0.08876, callQ='lit', tL=4299.13, group='SL', BQ=False),
    (3, 6): dict(win=(4729.05, 5588.87), P=0.00219, tP=5467.0, callP='dark', callK='dark', Q=0.07203, callQ='lit', tL=5158.96, group='SD', BQ=True),
    (3, 7): dict(win=(5588.87, 6448.7), P=0.01964, tP=5929.0, callP='dark', callK='tie', Q=0.0698, callQ='tie', tL=6018.79, group='-', BQ=False),
    (5, 7): dict(win=(3353.32, 3869.22), P=0.03266, tP=3641.0, callP='dark', callK='dark', Q=0.08665, callQ='lit', tL=3611.27, group='SD', BQ=True),
    (5, 8): dict(win=(3869.22, 4385.12), P=0.00669, tP=4006.5, callP='dark', callK='dark', Q=0.06104, callQ='tie', tL=4127.17, group='SD', BQ=False),
    (5, 9): dict(win=(4385.12, 4901.01), P=0.14523, tP=4653.0, callP='lit', callK='lit', Q=0.0932, callQ='lit', tL=4643.06, group='SL', BQ=False),
    (5, 10): dict(win=(4901.01, 5416.91), P=0.01357, tP=5416.5, callP='dark', callK='dark', Q=0.05679, callQ='tie', tL=5158.96, group='SD', BQ=False),
    (5, 11): dict(win=(5416.91, 5932.8), P=0.04518, tP=5652.0, callP='tie', callK='tie', Q=0.05578, callQ='tie', tL=5674.86, group='-', BQ=False),
    (5, 12): dict(win=(5932.8, 6448.7), P=0.03715, tP=6208.5, callP='tie', callK='dark', Q=0.0485, callQ='tie', tL=6190.75, group='-', BQ=False),
    (7, 1): dict(win=(184.25, 552.75), P=0.00013, tP=184.5, callP='dark', callK='dark', Q=0.20219, callQ='lit', tL=368.5, group='SD', BQ=True),
    (7, 2): dict(win=(552.75, 921.24), P=0.00042, tP=721.5, callP='dark', callK='dark', Q=0.17627, callQ='lit', tL=736.99, group='SD', BQ=True),
    (7, 3): dict(win=(921.24, 1289.74), P=0.00613, tP=1064.0, callP='dark', callK='tie', Q=0.18707, callQ='lit', tL=1105.49, group='-', BQ=False),
    (7, 4): dict(win=(1289.74, 1658.24), P=0.00481, tP=1420.5, callP='dark', callK='dark', Q=0.09967, callQ='lit', tL=1473.99, group='SD', BQ=True),
    (7, 5): dict(win=(1658.24, 2026.73), P=0.02791, tP=1813.0, callP='dark', callK='tie', Q=0.07757, callQ='tie', tL=1842.49, group='-', BQ=False),
    (7, 6): dict(win=(2026.73, 2395.23), P=0.00308, tP=2126.0, callP='dark', callK='dark', Q=0.12968, callQ='lit', tL=2210.98, group='SD', BQ=True),
    (7, 7): dict(win=(2395.23, 2763.73), P=0.0143, tP=2639.5, callP='dark', callK='dark', Q=0.09427, callQ='lit', tL=2579.48, group='SD', BQ=True),
    (7, 8): dict(win=(2763.73, 3132.23), P=0.0496, tP=2970.0, callP='tie', callK='dark', Q=0.06321, callQ='tie', tL=2947.98, group='-', BQ=False),
    (7, 9): dict(win=(3132.23, 3500.72), P=0.03205, tP=3334.5, callP='tie', callK='dark', Q=0.06788, callQ='tie', tL=3316.47, group='-', BQ=False),
    (7, 10): dict(win=(3500.72, 3869.22), P=0.03098, tP=3677.5, callP='tie', callK='dark', Q=0.06463, callQ='tie', tL=3684.97, group='-', BQ=False),
    (7, 11): dict(win=(3869.22, 4237.72), P=0.06513, tP=4078.0, callP='tie', callK='tie', Q=0.05542, callQ='tie', tL=4053.47, group='-', BQ=False),
    (7, 12): dict(win=(4237.72, 4606.21), P=0.02381, tP=4606.0, callP='dark', callK='dark', Q=0.06591, callQ='tie', tL=4421.97, group='SD', BQ=False),
    (7, 13): dict(win=(4606.21, 4974.71), P=0.10889, tP=4784.0, callP='lit', callK='lit', Q=0.0703, callQ='tie', tL=4790.46, group='SL', BQ=False),
    (7, 14): dict(win=(4974.71, 5343.21), P=0.02887, tP=5343.0, callP='dark', callK='dark', Q=0.05042, callQ='tie', tL=5158.96, group='SD', BQ=False),
    (7, 15): dict(win=(5343.21, 5711.71), P=0.04833, tP=5506.5, callP='tie', callK='tie', Q=0.04791, callQ='tie', tL=5527.46, group='-', BQ=False),
    (7, 16): dict(win=(5711.71, 6080.2), P=0.03735, tP=5918.0, callP='tie', callK='dark', Q=0.04815, callQ='tie', tL=5895.95, group='-', BQ=False),
    (7, 17): dict(win=(6080.2, 6448.7), P=0.03908, tP=6282.5, callP='tie', callK='dark', Q=0.04503, callQ='tie', tL=6264.45, group='-', BQ=False),
}
SL = [k for k, d in SLOTS.items() if d['group'] == 'SL']                  # 3 slots
SD = [k for k, d in SLOTS.items() if d['group'] == 'SD']                  # 12 slots
BQ = [k for k, d in SLOTS.items() if d['BQ']]                             # 8 slots
TIE = [k for k, d in SLOTS.items() if d['group'] == '-']                  # 12 slots
PLIT = [k for k, d in SLOTS.items() if d['callP'] == 'lit']               # 3 slots
assert len(SLOTS) == 27 and len(SL) == 3 and len(SD) == 12 and len(BQ) == 8 and len(TIE) == 12 and len(PLIT) == 3
assert not [k for k, d in SLOTS.items() if d['group'] in ('E', 'E2')]
NEED_B1, NEED_B2, NEED_D, FRAC = 2, 7, 10, 0.8


def window(c, r, lo, hi):
    m = (c >= lo) & (c <= hi)
    cc, rr = c[m], r[m]
    p = int(round(PERSIST / (c[1] - c[0])))
    if len(rr) < p + 1 or c[-1] < hi:
        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')
    return dict(status=status, statuses=st, height=float(np.mean([w['height'] for w in ws])),
                t_peak=float(np.mean([w['t_peak'] for w in ws])), heights=[w['height'] for w in ws],
                t_peaks=[w['t_peak'] for w in ws])


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', r.get('theta') == 0.40 and r.get('mu') == 2.0 and r.get('N') == 2560)) 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 count(S, keys, status):
    return sum(S[k]['status'] == status for k in keys)


def main(res):
    res = Path(res)
    recs = [json.loads(p.read_text()) for p in sorted((res / 'run_records').glob('MQG9T-*.json'))]
    print(f'MQG test 9T 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['verdict'] = f'incomplete: {len(recs)} rows, the plan needs 5'; 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]}'], *d['win']) for z in ser]) for k, d in SLOTS.items()}
    print('The test slots (t_x = X t_K/m; peak as t/t_K; SL = P and K lit, SD = P and K dark, BQ = SD with Q lit, - = a tie):')
    for k, d in SLOTS.items():
        e = S[k]; g = d['group'] + ('/BQ' if d['BQ'] else '')
        print(f'  ({k[0]},{k[1]:2d}) {g:5s} {e["status"]:11s} height {e["height"]:+.4f} peak {e["t_peak"] / T_K:.4f}'
              f' | P {d["P"]:.4f} ({d["callP"]}) at {d["tP"] / T_K:.4f}  K {d["callK"]}  Q {d["Q"]:.4f} ({d["callQ"]})  L at {d["tL"] / T_K:.4f}')
    nr = [k for k in SL + SD if S[k]['status'] == 'not reached']
    if nr:
        ruleB1 = ruleB2 = f'windows not reached at {nr}: the primary rules do not decide'
    else:
        n1p, n1a = count(S, SL, 'present'), count(S, SL, 'absent')
        if n1p >= NEED_B1 and n1a == 0:
            ruleB1 = f'{n1p} of the 3 shared lit slots present, none absent: P and K favoured over A'
        elif n1a >= NEED_B1 and n1p == 0:
            ruleB1 = f'{n1a} of the 3 shared lit slots absent, none present: A favoured over P and K'
        else:
            ruleB1 = f'neither ({n1p} present, {n1a} absent of 3)'
        n2a, n2p = count(S, BQ, 'absent'), count(S, BQ, 'present')
        if n2a >= NEED_B2:
            ruleB2 = f'{n2a} of the 8 slots of group BQ absent: P and K favoured over Q'
        elif n2p >= NEED_B2:
            ruleB2 = f'{n2p} of the 8 slots of group BQ present: Q favoured over P and K'
        else:
            ruleB2 = f'neither ({n2a} absent, {n2p} present of 8)'
    print('Primary rule B1:', ruleB1); print('Primary rule B2:', ruleB2)
    nDa = count(S, SD, 'absent')
    secD = f'{nDa} of the 12 shared dark slots absent: ' + ('holds' if nDa >= NEED_D else 'fails') + f' (pass mark {NEED_D})'
    print('Secondary rule D:', secD)
    checks = []
    print('Secondary rule H (heights of P on its 3 lit slots; factor 1.3, rank 7 factor 1.5):')
    for k in PLIT:
        f = 1.5 if k[0] == 7 else 1.3; h, pp = S[k]['height'], SLOTS[k]['P']
        ok = h == h and 1 / f <= h / pp <= f
        checks.append(dict(check=f'{k} height', holds=bool(ok), detail=f'{h:.4f} against P {pp:.4f} (factor {f})'))
        print(f'  {"holds" if ok else "FAILS"}: {k} height: {h:.4f} against P {pp:.4f} (factor {f})')
    nh = sum(c['holds'] for c in checks)
    secH = f'P heights within tolerance in {nh} of {len(checks)} slots: ' + ('holds' if nh >= FRAC * len(checks) else 'fails') + ' (pass mark 80%)'
    print(secH)
    timing = []
    for k in PLIT:
        d, e = SLOTS[k], S[k]
        if e['status'] != 'present' or abs(d['tP'] - d['tL']) < 0.01 * T_K:
            continue
        closer = 'P' if abs(e['t_peak'] - d['tP']) < abs(e['t_peak'] - d['tL']) else 'L'
        timing.append(dict(slot=list(k), t_peak=e['t_peak'], tP=d['tP'], tL=d['tL'], closer=closer))
    nP = sum(t['closer'] == 'P' for t in timing)
    if len(timing) < 3:
        secT = f'only {len(timing)} lit slots where P and L differ by at least 0.01 t_K: the rule does not decide'
    elif nP >= FRAC * len(timing):
        secT = f'{nP} of {len(timing)} peak times closer to P than to L: P favoured over L'
    elif len(timing) - nP >= FRAC * len(timing):
        secT = f'{len(timing) - nP} of {len(timing)} peak times closer to L than to P: L favoured over P'
    else:
        secT = f'neither P nor L ({nP} closer to P, {len(timing) - nP} closer to L)'
    print('Secondary rule T (timing):', secT)
    cons = [list(k) for k in SL if S[k]['status'] == 'present'
            and np.max(np.abs(np.array(S[k]['t_peaks']) / S[k]['t_peak'] - 1)) > 0.02]
    print('Replicate peak times of present SL slots within 2% of their means:', 'yes' if not cons else f'no at {cons}')
    ties = {f'{k[0]} {k[1]}': S[k]['status'] for k in TIE}
    print('Tie slots (reported only):', ties)
    out.update(primary_rule_B1=ruleB1, primary_rule_B2=ruleB2, secondary_D=secD, secondary_H=secH, secondary_T=secT,
               timing=timing, checks=checks, consistency_failures=cons, ties=ties,
               slots={f'{k[0]} {k[1]}': v for k, v in S.items()})
    return out


def selftest():
    """Synthetic rows for every branch: B1 favoured / A / neither; B2 favoured / Q / neither; D, H, T; not reached; void; incomplete."""
    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, theta=0.40, mu=2.0, N=2560, deposit_doi='10.5281/zenodo.TEST')
    c = np.round(np.arange(15.0, 6485.0 + 0.25, 0.5), 10)
    def make(tmp, lit, tmax=6485.0, nrows=5, edit=None, height=None, shift=0.0):
        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'MQG9T-{i:02d}'; ser = {f'D{m}': np.zeros_like(cc) for m in range(1, 8)}
            for k, dd in SLOTS.items():
                if k in lit:
                    h = height.get(k, dd['P']) if height else max(dd['P'], 0.1)
                    t0 = dd['tP'] + shift
                    ser[f'D{k[0]}'] += h * np.exp(-0.5 * ((cc - t0) / 20.0) ** 2)
            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)
    res = []
    def case(name, cond):
        res.append((name, bool(cond))); print(('PASS ' if cond else 'FAIL ') + name)
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set(SL)); case('B1 favoured, B2 favoured, D holds, H holds', 'P and K favoured over A' in o['primary_rule_B1']
            and 'P and K favoured over Q' in o['primary_rule_B2'] and o['secondary_D'].endswith('(pass mark 10)') and 'holds' in o['secondary_D'] and ': holds' in o['secondary_H'])
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set()); case('A favoured over P and K', 'A favoured over P and K' in o['primary_rule_B1'])
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit={SL[0]}); case('B1 neither (1 present, 2 absent)', o['primary_rule_B1'].startswith('neither'))
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set(SL) | set(BQ)); case('Q favoured over P and K; D fails', 'Q favoured over P and K' in o['primary_rule_B2'] and 'fails' in o['secondary_D'])
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set(SL) | set(BQ[:3])); case('B2 neither (5 absent, 3 present)', o['primary_rule_B2'].startswith('neither'))
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set(SL), height={k: 2.0 * SLOTS[k]['P'] for k in SL}); case('H fails (heights twice P)', ': fails' in o['secondary_H'])
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set(SL)); case('T does not decide (one slot where P and L differ)', 'does not decide' in o['secondary_T'])
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set(SL), tmax=6000.0); case('not reached: primary rules do not decide', 'do not decide' in o['primary_rule_B1'])
    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(deposit_doi='other'), 'deposit DOI')):
        with tempfile.TemporaryDirectory() as t:
            o = make(t, lit=set(SL), edit=ed); case(f'void on {label}', o.get('verdict', '').startswith('void'))
    with tempfile.TemporaryDirectory() as t:
        o = make(t, lit=set(SL), nrows=4); case('incomplete with 4 rows', o.get('verdict', '').startswith('incomplete'))
    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() else 1)
    res = sys.argv[1]
    o = main(res)
    Path(res, 'MQG_TEST_9T_SCORE.json').write_text(json.dumps(o, indent=2), encoding='utf-8')
