"""MQG test 9T: the frozen predictions (written 2026-11-30). Spectra and classical quantities only; no exact or TWA dynamics.

State of test 9 (doi:10.5281/zenodo.24022511): two-beam collective-neutrino model, mu = 2, theta = 0.40, N = 2560,
L = 0 coherent state. Test 9 recorded ranks 1-6 to t = 3300. Test 9T extends the record to t = 6500 and adds rank 7.
Slots (m, X) of the odd ranks m = 1, 3, 5, 7 sit at t_x = X t_K/m (window (X -/+ 1/2) t_K/m, spectral t_K). Test slots:
rank 7 at every X whose window ends by 6500; ranks 1, 3 and 5 only where the whole window lies in [3300, 6500], which test 9
never recorded. For every odd slot it gives
  P : spectral two-clock rule (nu_oddrule.rule, variant 'T': odd blocks half a level up), height H = m^(1/3) max_window G_m
      of the running mean (width 30) of G_m, and the peak time t_P;
  Q : the same without the half-level offset (variant 'Q');
  K : two-key rule of test 13 (mqg_test13_predict.clocks, unchanged): odd X only (half-layer point x = X/2); bands k > 0
      whose classical Fourier weight of s_+^m along the L = 0 orbit (k and -k together) is at least 15% of the rank's total;
      level point j = 1; mismatch |t_j/t_x - 1| with t_j = t_spec/k and t_x = X t_K/m (classical clocks); lit if some band
      has mismatch <= 0.15, dark if all have >= 0.25, tie otherwise; even X: dark; peak t* = (m^2 t_x + 4k^2 t_j)/(m^2+4k^2);
  L : nominal hour t_L = X t_K/m;   A : every odd slot dark.
Calls (test 24): lit H >= 0.07, dark H <= 0.035; rank 7: lit >= 0.08, dark <= 0.03; tie between.
Groups (test slots only): SL (P lit, K lit), SD (P dark, K dark), E (P lit, K dark), E2 (P dark, K lit); BQ = SD slots where
Q is lit. Slots where P or K is tie belong to no group.
Run: python -I mqg_test9T_predict.py <folder with nu_oddrule.py, mqg_test13_predict.py, mqg_step2_robustness.py>
Writes mqg_test9T_predictions.json next to this file."""
import sys, os, json, hashlib, numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
SRC = sys.argv[1] if len(sys.argv) > 1 else HERE
sys.path.insert(0, SRC)
_a = sys.argv; sys.argv = _a[:1]
import mqg_test13_predict as T13
sys.argv = _a
import nu_oddrule as R
from scipy.integrate import solve_ivp

N, MU, THETA, T_MAX, T9_MAX, DT, RANKS = 2560, 2.0, 0.40, 6500.0, 3300.0, 0.5, (1, 3, 5, 7)

def calls(H, m):
    lo, hi = (0.03, 0.08) if m == 7 else (0.035, 0.07)
    return 'lit' if H >= hi else ('dark' if H <= lo else 'tie')

def band_sets(mu, theta, T0, nper=40):
    Bx, Bz = np.sin(2*theta), np.cos(2*theta); al = 2*theta
    def f(t, y):
        a, c = y[:3], y[3:]; h = mu/2*(a + c)
        return np.concatenate([np.cross(h + np.array([Bx, 0, Bz]), a), np.cross(h - np.array([Bx, 0, Bz]), c)])
    Ttot = nper*T0; ts = np.linspace(0, Ttot, int(nper*400) + 1)
    s = solve_ivp(f, (0, Ttot), [0, 0, 1, 0, 0, -1.0], t_eval=ts, method='DOP853', rtol=1e-11, atol=1e-12)
    S = s.y[:3] + s.y[3:]; sp = (np.cos(al)*S[0] - np.sin(al)*S[2]) + 1j*S[1]; w = 2*np.pi/T0
    out, weights = {}, {}
    for m in RANKS:
        ks = np.arange(-(m + 4)/2, (m + 4)/2 + 0.01, 0.5)
        c = np.array([np.trapezoid(sp**m*np.exp(-1j*k*w*ts), ts)/Ttot for k in ks]); W = np.abs(c)/np.abs(c).sum()
        out[m] = [float(k) for k, v in zip(ks, W) if k > 0 and 2*v >= 0.15]
        weights[m] = {f'{k:+.1f}': float(v) for k, v in zip(ks, W) if v >= 0.005}
    return out, weights

def K_call(m, X, tKc, tsc, kset):
    if X % 2 == 0: return 'dark', None, None, None
    tx = X*tKc/m; best = None
    for k in kset:
        tj = tsc/k; mis = abs(tj/tx - 1)
        if best is None or mis < best[0]: best = (mis, (m*m*tx + 4*k*k*tj)/(m*m + 4*k*k), k)
    mis = best[0]
    return ('lit' if mis <= 0.15 else ('dark' if mis >= 0.25 else 'tie')), mis, best[1], best[2]

def main():
    sha = {f: hashlib.sha256(open(os.path.join(SRC, f), 'rb').read()).hexdigest()
           for f in ('nu_oddrule.py', 'mqg_test13_predict.py', 'mqg_step2_robustness.py')}
    sha['mqg_test9T_predict.py'] = hashlib.sha256(open(os.path.abspath(__file__), 'rb').read()).hexdigest()
    d = R.spectra(N, MU, THETA, mmax=7)
    T13.N = N
    T0, jEnn, jkk, tKc, tsc = T13.clocks(MU, THETA)
    ksets, bw = band_sets(MU, THETA, T0)
    T = np.arange(0.0, T_MAX + DT, DT); slots = []
    for m in RANKS:
        GP = R.smooth(R.rule(d, m, T, 'T'), DT); GQ = R.smooth(R.rule(d, m, T, 'Q'), DT)
        X = 1
        while (X + 0.5)*d['tK']/m <= T_MAX:
            lo, hi = (X - 0.5)*d['tK']/m, (X + 0.5)*d['tK']/m
            sel = (T >= lo) & (T <= hi); i = int(np.argmax(GP[sel]))
            HP = m**(1/3)*float(GP[sel][i]); tP = float(T[sel][i]); HQ = m**(1/3)*float(GQ[sel].max())
            kc, mis, ts_, kb = K_call(m, X, tKc, tsc, ksets[m]); cp, cq = calls(HP, m), calls(HQ, m)
            test = (m == 7) or (lo >= T9_MAX)
            grp = {('lit', 'lit'): 'SL', ('dark', 'dark'): 'SD', ('lit', 'dark'): 'E', ('dark', 'lit'): 'E2'}.get((cp, kc), '-') if test else 'not a test slot'
            slots.append(dict(m=m, X=X, window=[round(lo, 2), round(hi, 2)], t_L=round(X*d['tK']/m, 2), test_slot=test,
                              H_P=round(HP, 5), call_P=cp, t_P=tP, H_Q=round(HQ, 5), call_Q=cq, call_K=kc,
                              K_mismatch=None if mis is None else round(mis, 4), K_tstar=None if ts_ is None else round(ts_, 1),
                              K_band=kb, group=grp, BQ=bool(test and grp == 'SD' and cq == 'lit')))
            X += 1
    out = dict(test='MQG test 9T', N=N, mu=MU, theta=THETA, T_max=T_MAX, test9_T_max=T9_MAX, dt=DT,
               spectral_tK=d['tK'], spectral_2pi_over_eII=d['tL'], R_spec=d['tL']/d['tK'], classical_tK=tKc,
               classical_tspec=tsc, R_cl=tsc/tKc, T_cl=T0, label_rms_checkerboard=d['fits']['checkerboard n_top+|K|/2']['rms'],
               label_rms_square=d['fits']['square n_top']['rms'], K_bands={str(m): v for m, v in ksets.items()},
               band_weights={str(m): v for m, v in bw.items()}, slots=slots, sha256=sha, numpy=np.__version__)
    json.dump(out, open(os.path.join(HERE, 'mqg_test9T_predictions.json'), 'w'), indent=1)
    print(f"spectral t_K {d['tK']:.2f}  2pi/|e_II| {d['tL']:.2f}  R {d['tL']/d['tK']:.4f} | classical t_K {tKc:.2f} t_spec {tsc:.2f} "
          f"R {tsc/tKc:.4f} | label rms checkerboard {out['label_rms_checkerboard']:.1e} square {out['label_rms_square']:.1e} | K bands {out['K_bands']}")
    print(" slot     window            t_L      H_P   P     t_P      H_Q   Q     K    mis     t*      group   BQ")
    for s in slots:
        ks = f"{s['call_K']:4s} " + (f"{s['K_mismatch']:.3f} {s['K_tstar']:7.1f}" if s['K_mismatch'] is not None else " " * 13)
        print(f" ({s['m']},{s['X']:2d})  {s['window'][0]:7.1f}-{s['window'][1]:7.1f}  {s['t_L']:7.1f}  {s['H_P']:.4f} {s['call_P']:4s} {s['t_P']:7.1f}  "
              f"{s['H_Q']:.4f} {s['call_Q']:4s}  {ks}  {s['group'] if s['test_slot'] else '(test 9 window)':8s} {'BQ' if s['BQ'] else ''}")
    g = [s['group'] for s in slots if s['test_slot']]
    print(f"test slots {len(g)}: SL {g.count('SL')}, SD {g.count('SD')} (BQ {sum(s['BQ'] for s in slots)}), E {g.count('E')}, E2 {g.count('E2')}, no group {g.count('-')}")
    print("sha256:", json.dumps(sha))

if __name__ == '__main__':
    main()
