#!/usr/bin/env python3
"""MQG test 30: frozen predictions (2 Dec 2026; edge rule for CURV, CURV_R, CX1 and CX2 and rounded even returns, 3 Dec 2026). Exact block spectra and the classical orbit only; no exact or TWA dynamics.

State: two-beam collective-neutrino model, mu = 3.0, theta = 0.15, N = 1280 (j = 320), L = 0 coherent state. Odd ranks
m = 1, 3, 5, 7; slots (m, X) at t_L = X t_K/m with windows (X -+ 1/2) t_K/m (spectral t_K), every slot whose window ends by
2.5 t_K. Curves on a grid of step 0.5 to T_MAX = 600, running mean of width 30 (as in test 28).
For each slot:
  Ha   coherent height with the fitted two-clock energies (nu_height.coherent_curve, variant 'T'; rule P of test 28), minus the
       floor f_m; t_Pa the time of its maximum in the window
  Hx   the same formula with the exact eigenvalue differences (mqg_test28_Hx.envelopes_exact, unchanged); t_Px
  Lin  the same formula with the exact eigenvalue differences of each class replaced by their weighted linear fit in (K, x)
       (envelopes_linear below; Step A's linear two-clock variant); t_PL
  C    rival C: the classical two-key rule K of tests 12, 13 and 28 (mqg_test28_predict.band_sets and K_call, unchanged)
  L    the nominal hour t_L
Calls (test 28): lit if H >= 0.07, dark if H <= 0.035; rank 7: 0.08 and 0.03; otherwise tie.
Groups (frozen here, used by mqg_test30_score.py):
  TX   Hx lit, |t_Px - t_Pa| >= max(5, 0.01 t_K), and both t_Px and t_Pa at least 2.5 from each window edge   (primary)
  TL   Hx lit, |t_Px - t_L| >= max(5, 0.01 t_K), and t_Px at least 2.5 from each window edge                 (secondary)
  CURV Hx lit, Lin dark;  CURV_R  Hx dark, Lin lit; both with t_Px at least 2.5 from each window edge          (secondary)
  CX1  Hx lit, C dark;  CX2  Hx dark, C lit; both only where t_Px lies at least 0.12 t_K from every even-rank return
       (multiples of t_K/3 and t_K/2, which include those of t_K) and at least 2.5 from each window edge       (reported only)
  SD   Hx, Ha and Lin all dark                                                                                   (secondary)
Run: python -I mqg_test30_predict.py <modules folder>   (writes mqg_test30_predictions.json next to this file)"""
import sys, os, json, hashlib
HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(HERE, 'modules')
sys.path.insert(0, SRC)
_a = sys.argv; sys.argv = _a[:1]                # mqg_test13_predict reads sys.argv[1] (states) at import
import numpy as np
import nu_oddrule as R, nu_height as NH, mqg_moments as MM, mqg_test13_predict as T13
sys.argv = [_a[0], SRC]                          # mqg_test28_predict and mqg_test28_Hx read sys.argv[1] (module folder)
import mqg_test28_predict as P28, mqg_test28_Hx as HX
sys.argv = _a

N, MU, THETA, T_MAX, SLOT_END, DT, RANKS, M = 1280, 3.0, 0.15, 600.0, 2.5, 0.5, (1, 3, 5, 7), 8000
EDGE, SEP_ABS, SEP_REL, EVEN_SEP = 2.5, 5.0, 0.01, 0.12
MODULES = ('nu_oddrule.py', 'nu_height.py', 'mqg_moments.py', 'mqg_step2_robustness.py', 'mqg_test13_predict.py',
           'mqg_test28_predict.py', 'mqg_test28_Hx.py')


def envelopes_linear(d, md, m, T, min_class=1e-3):
    """As HX.envelopes_exact, but the exact eigenvalue differences of each class are replaced by their weighted linear fit
    dE = c0 + c1 K + c2 x (same levels, same Gaussian weights)."""
    sK, sI, Kf = d['sdK'], d['sI'], d['Kfit']
    Wm = {h: v for (mm, h), v in d['W'].items() if mm == m}; tot = sum(Wm.values())
    xr = int(np.ceil(5 * sI)) + 3; Kg = np.arange(-Kf, Kf + 1)
    keys = sorted(d['Ibar'], key=abs); absk = [abs(k) for k in keys]; vals = [d['Ibar'][k] for k in keys]
    out, coef = {}, {}
    for h, v in Wm.items():
        if v / tot < min_class:
            continue
        Ks, xs_all, dEs, ws = [], [], [], []
        for K in Kg:
            off = abs(K) / 2 % 1
            cen = np.interp(abs(K), absk, vals); xs = np.round(cen) + np.arange(-xr, xr + 1) + off
            wgt = np.exp(-K ** 2 / (2 * sK ** 2)) * np.exp(-(xs - cen) ** 2 / (2 * sI ** 2))
            E1, E2 = md.eig(int(K))[0], md.eig(int(K + m))[0]
            n1 = np.round(xs + d['I0'] - abs(K) / 2).astype(int); n2 = np.round(xs + h + d['I0'] - abs(K + m) / 2).astype(int)
            ok = (n1 >= 0) & (n1 < len(E1)) & (n2 >= 0) & (n2 < len(E2))
            Ks.append(np.full(ok.sum(), float(K))); xs_all.append(xs[ok]); dEs.append(E2[n2[ok]] - E1[n1[ok]]); ws.append(wgt[ok])
        K_, x_, dE, w = map(np.concatenate, (Ks, xs_all, dEs, ws))
        A = np.ascontiguousarray(np.stack([np.ones_like(K_), K_, x_], 1)); sw = np.sqrt(w)
        c, *_ = np.linalg.lstsq(A * sw[:, None], dE * sw, rcond=None)
        out[h] = (w[None, :] * np.exp(1j * np.outer(T, A @ c))).sum(1) / w.sum()
        coef[str(h)] = [float(x) for x in c]
    return out, coef


def main():
    sha = {f: hashlib.sha256(open(os.path.join(SRC, f), 'rb').read()).hexdigest() for f in MODULES}
    sha['mqg_test30_predict.py'] = hashlib.sha256(open(os.path.abspath(__file__), 'rb').read()).hexdigest()
    d = R.spectra(N, MU, THETA, mmax=7, keep_cache=True); md = d['model']
    W, S = NH.signed_weights(d, 7)
    T13.N = N
    T0, jEnn, jkk, tKc, tsc = T13.clocks(MU, THETA)
    ksets, bw = P28.band_sets(MU, THETA, T0)
    nab, _ = MM.orbit_norms(MU, THETA, mmax=14); j = N / 4
    tK = d['tK']; T = np.arange(0.0, T_MAX + DT, DT)
    even = sorted({round(p * tK / q, 9) for q in (2, 3) for p in range(0, 9) if p / q <= SLOT_END + 0.5})   # rounded: equal returns merge on every platform
    slots, lin_coef = [], {}
    for m in RANKS:
        Qm, fm = j ** m * nab[m], NH.floor(nab, m, M)
        GA = NH.coherent_curve(d, S, m, T, Qm, 'T', DT)
        Ax, lost = HX.envelopes_exact(d, md, m, T)
        GX = R.smooth(np.abs(sum(S[(m, h)] * a for h, a in Ax.items())) / Qm, DT)
        Al, lin_coef[str(m)] = envelopes_linear(d, md, m, T)
        GL = R.smooth(np.abs(sum(S[(m, h)] * a for h, a in Al.items())) / Qm, DT)
        X = 1
        while (X + 0.5) / m <= SLOT_END + 1e-12:
            lo, hi = (X - 0.5) * tK / m, (X + 0.5) * tK / m; sel = (T >= lo) & (T <= hi); tL = X * tK / m
            (Ha, tPa), (Hx, tPx), (Hl, tPl) = ((float(G[sel].max()) - fm, float(T[sel][int(np.argmax(G[sel]))])) for G in (GA, GX, GL))
            ca, cx, cl = P28.calls(Ha, m), P28.calls(Hx, m), P28.calls(Hl, m)
            kc, mis, kts, kb = P28.K_call(m, X, tKc, tsc, ksets[m])
            dev = min(abs(tPx - e) for e in even) / tK
            inner = lambda t: min(t - lo, hi - t) >= EDGE
            sep = max(SEP_ABS, SEP_REL * tK)
            g = []
            if cx == 'lit' and abs(tPx - tPa) >= sep and inner(tPx) and inner(tPa): g.append('TX')
            if cx == 'lit' and abs(tPx - tL) >= sep and inner(tPx): g.append('TL')
            if cx == 'lit' and cl == 'dark' and inner(tPx): g.append('CURV')
            if cx == 'dark' and cl == 'lit' and inner(tPx): g.append('CURV_R')
            if dev >= EVEN_SEP and cx == 'lit' and kc == 'dark' and inner(tPx): g.append('CX1')
            if dev >= EVEN_SEP and cx == 'dark' and kc == 'lit' and inner(tPx): g.append('CX2')
            if cx == ca == cl == 'dark': g.append('SD')
            slots.append(dict(m=m, X=X, window=[round(lo, 2), round(hi, 2)], t_L=round(tL, 2),
                              Hx=round(Hx, 5), call_x=cx, t_Px=tPx, Ha=round(Ha, 5), call_a=ca, t_Pa=tPa,
                              Lin=round(Hl, 5), call_lin=cl, t_PL=tPl, call_C=kc,
                              C_mismatch=None if mis is None else round(mis, 4), C_band=kb, even_sep=round(dev, 4),
                              floor=round(fm, 5), lost_weight=round(float(lost), 6), groups=g))
            X += 1
    out = dict(test='MQG test 30', N=N, mu=MU, theta=THETA, T_max=T_MAX, slot_end_over_tK=SLOT_END, dt=DT, M=M,
               edge=EDGE, sep_abs=SEP_ABS, sep_rel=SEP_REL, even_sep_min=EVEN_SEP,
               spectral_tK=tK, spectral_2pi_over_eII=d['tL'], R_spec=d['tL'] / 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'], C_bands={str(m): v for m, v in ksets.items()},
               band_weights={str(m): v for m, v in bw.items()}, orbit_norms={str(m): nab[m] for m in range(1, 15)},
               even_returns=[round(e, 3) for e in even], lin_coefficients=lin_coef, slots=slots, sha256=sha,
               numpy=np.__version__)
    json.dump(out, open(os.path.join(HERE, 'mqg_test30_predictions.json'), 'w'), indent=1,
              default=lambda x: x.item() if hasattr(x, 'item') else str(x))
    print(f"spectral t_K {tK:.3f}  2pi/|e_II| {d['tL']:.3f}  R {d['tL'] / 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} | C bands {out['C_bands']}")
    print(" slot     window           t_L     Hx      x     t_Px    Ha      a     t_Pa    Lin     lin   C    e-sep  groups")
    for s in slots:
        print(f" ({s['m']},{s['X']:2d})  {s['window'][0]:6.1f}-{s['window'][1]:6.1f}  {s['t_L']:6.1f}  {s['Hx']:+.4f} {s['call_x']:4s} {s['t_Px']:6.1f}  "
              f"{s['Ha']:+.4f} {s['call_a']:4s} {s['t_Pa']:6.1f}  {s['Lin']:+.4f} {s['call_lin']:4s} {s['call_C']:4s} {s['even_sep']:.3f}  {' '.join(s['groups'])}")
    for gname in ('TX', 'TL', 'CURV', 'CURV_R', 'CX1', 'CX2', 'SD'):
        mem = [f"({s['m']},{s['X']})" for s in slots if gname in s['groups']]
        print(f"{gname}: {len(mem)} {' '.join(mem)}")
    print("orbit norms:", {m: round(nab[m], 6) for m in range(1, 8)})
    print("sha256:", json.dumps(sha))


if __name__ == '__main__':
    main()
