#!/usr/bin/env python3
"""MQG test 9T runner: the powers <J+^m>, m = 1..7, at theta = 0.40, mu = 2, N = 2560, to t = 6500, written 2026-11-30.

Computes the 5 rows of MQG_TEST_9T_PUBLIC_PLAN (MQG9T-01 to MQG9T-05, one per TWA replicate). The exact powers
<J+^m>(t) come from mqg_moments.exact_powers, the block algorithm of the Paper 2 solver (mqg_step2_robustness.py,
imported unchanged); they are computed once and cached. Each row draws a gaussian TWA ensemble with the solver's
sampling and equations (mqg_moments.twa_powers) and, for every m, forms
    D_m(t) = (|<J+^m>_exact| - |<J+^m>_TWA|) / (j^m <|S_perp|^m>_T),
with the orbit norms of the plan. The running mean over 30 time units and the return time (start of the first
interval of length at least 10 with the running mean at or above 0.05) are those of the Paper 2 development runner
(p2_development_runner_colab_v2.py, imported unchanged): running_excess(1 + D_m, 1) is exactly the running mean of D_m.

Guards
  * Refuses to run without --deposit-doi, the DOI of the deposited public plan.
  * Recomputes the coherent spectral time and the orbit norms and stops if either differs from the plan.
  * Refuses to run unless NumPy is 2.4.6 and the development runner uses M = 8000 TWA samples.
  * Estimates the memory of the exact step and refuses a cell that would not fit.
  * Writes each row once; a rerun skips rows already written, so it is safe after a disconnect.
  * A smoke mode (--smoke-theta, --smoke-tmax, --sizes) runs at another angle and size with a short window, to test
    the pipeline only, and writes only to --output-dir. Its rows are marked smoke and the scorer refuses them.
The running mean of D_m (width 30) is saved for every row and rank in series/<run_id>.npz, as in test 24.
This file differs from mqg_test09_runner.py (doi:10.5281/zenodo.24022511) only in the ranks (MMAX = 7), the window
(T_MAX = 6500), the seeds, the plan norm of rank 7, the NumPy version, the run labels, the file names and the saved series.
It does not score. The frozen scoring rules are in mqg_test9T_score.py.
"""
from pathlib import Path
import argparse, csv, hashlib, importlib.util, json, math, platform, sys
from datetime import datetime, timezone
import numpy as np

BASE = Path('/content/drive/MyDrive/P2_KAPPA_PREREGISTRATION')
THETA, MU, SIZES, MMAX = 0.40, 2.0, (2560,), 7
REPLICATES, SEED0, T_MAX = 5, 20272901, 6500.0
PLAN_TSPEC = {2560: 2338.43}
PLAN_NORMS = {1: 1.12897, 2: 1.64864, 3: 2.65017, 4: 4.47348, 5: 7.77489, 6: 13.77555, 7: 24.74186}


def load(path, name):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def sha256(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def available_memory_gb():
    try:
        for line in open('/proc/meminfo'):
            if line.startswith('MemAvailable:'):
                return int(line.split()[1]) / 1e6
    except Exception:
        return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--input-dir', default=str(BASE / 'inputs'))
    ap.add_argument('--output-dir', default='')
    ap.add_argument('--deposit-doi', default='')
    ap.add_argument('--sizes', default='', help=argparse.SUPPRESS)             # smoke tests only
    ap.add_argument('--smoke-theta', type=float, default=None, help=argparse.SUPPRESS)
    ap.add_argument('--smoke-tmax', type=float, default=None, help=argparse.SUPPRESS)
    args, _ = ap.parse_known_args()
    smoke = args.smoke_theta is not None
    if smoke and (args.smoke_tmax is None or not args.sizes or not args.output_dir):
        raise SystemExit('STOP: a smoke test needs --smoke-theta, --smoke-tmax, --sizes and --output-dir.')
    if smoke and abs(args.smoke_theta - THETA) < 1e-9:
        raise SystemExit('STOP: a smoke test must not use the test angle.')
    if not args.deposit_doi.strip():
        raise SystemExit('STOP: give --deposit-doi of the deposited public plan before any test-9T row.')
    theta = args.smoke_theta if smoke else THETA
    out = Path(args.output_dir) if args.output_dir else BASE / 'mqg_test9T'

    inp = Path(args.input_dir)
    rv_path, solver_path, mm_path = (inp / 'p2_development_runner_colab_v2.py', inp / 'mqg_step2_robustness.py',
                                     inp / 'mqg_moments.py')
    rv, solver, mm = load(rv_path, 'p2_dev_runner_v2'), load(solver_path, 'mqg_solver'), load(mm_path, 'mqg_moments')
    import scipy
    env = dict(runner_sha256=sha256(Path(__file__)), solver_sha256=sha256(solver_path),
               dev_runner_sha256=sha256(rv_path), moments_sha256=sha256(mm_path), numpy_version=np.__version__,
               scipy_version=scipy.__version__, deposit_doi=args.deposit_doi.strip(), smoke=smoke)
    print('environment:', json.dumps(env, indent=1), flush=True)
    if not smoke and np.__version__ != '2.4.6':
        raise SystemExit(f'STOP: NumPy {np.__version__}; the plan fixes NumPy 2.4.6.')
    if not smoke and rv.DEFAULT_M != 8000:
        raise SystemExit(f'STOP: the development runner uses M = {rv.DEFAULT_M}; the plan fixes M = 8000.')

    sizes = tuple(int(x) for x in args.sizes.split(',')) if args.sizes else SIZES
    t_max = args.smoke_tmax if smoke else T_MAX
    times = np.round(np.arange(0.0, t_max + rv.DT / 2, rv.DT), 10)
    exact_dir, rec_dir, ser_dir = out / 'exact_cache', out / 'run_records', out / 'series'
    exact_dir.mkdir(parents=True, exist_ok=True)
    rec_dir.mkdir(exist_ok=True)
    ser_dir.mkdir(exist_ok=True)

    nab, _ = mm.orbit_norms(MU, theta, MMAX)
    if not smoke:
        bad = {m: nab[m] for m in PLAN_NORMS if abs(nab[m] / PLAN_NORMS[m] - 1) > 1e-4}
        if bad:
            raise SystemExit(f'STOP: orbit norms {bad} differ from the plan {PLAN_NORMS}.')

    rows, i = [], 0
    for N in sizes:
        tspec = float(solver.spectral_time(N, MU, 1, theta))
        print(f'spectral time (coherent state) theta={theta} N={N}: {tspec:.2f}', flush=True)
        if not smoke and abs(tspec - PLAN_TSPEC[N]) > 0.01:
            raise SystemExit(f'STOP: t_spec at N={N} is {tspec:.4f}, the plan says {PLAN_TSPEC[N]}.')
        j = N / 4
        exact_file = exact_dir / f'exact_powers_th{theta:.2f}_N{N}_T{t_max:.1f}.npz'
        if exact_file.exists():
            z = np.load(exact_file)
            Jpm, normdev = z['Jpm'], float(z['normdev'])
        else:
            need = (MMAX + 3) * (N // 2 + 1) * len(times) * 16 / 1e9
            have = available_memory_gb()
            print(f'exact step N={N}: about {need:.1f} GB needed, {have} GB available', flush=True)
            if have is not None and need > 0.9 * have:
                raise MemoryError(f'N={N} needs about {need:.1f} GB; only {have:.1f} GB available')
            ex = mm.exact_powers(solver, N, MU, theta, times, mmax=MMAX)
            Jpm, normdev = ex['Jpm'], float(np.max(np.abs(ex['norm'] - 1.0)))
            np.savez_compressed(exact_file, times=times, Jpm=Jpm, norm=ex['norm'], JmJp=ex['JmJp'], normdev=normdev)
            print(f'exact step N={N} done, largest norm deviation {normdev:.1e}', flush=True)
        for rep in range(1, REPLICATES + 1):
            i += 1
            row = dict(run_id=f'MQG9T-{i:02d}', theta=theta, mu=MU, N=N, replicate=rep, seed=SEED0 + i - 1)
            rows.append(row)
            rec_path = rec_dir / f"{row['run_id']}.json"
            if rec_path.exists():
                continue
            tw = mm.twa_powers(N, MU, theta, times, M=rv.DEFAULT_M, substeps=rv.DEFAULT_SUBSTEPS, seed=row['seed'],
                               mmax=MMAX)
            per_m, series = {}, {}
            for m in range(1, MMAX + 1):
                Q = j ** m * nab[m]
                D = mm.excess(Jpm[m - 1], tw['Jpm'][m - 1], Q)
                centers, r = rv.running_excess(1.0 + D, np.ones_like(D), times)
                endpoint = rv.classify_survival_gate(centers, r)
                per_m[str(m)] = dict(endpoint, norm_Q=Q, max_running_excess=float(np.max(r)),
                                     t_at_max=float(centers[int(np.argmax(r))]), D_t0=float(D[0]))
                series[f'D{m}'] = r.astype(np.float64)
            np.savez_compressed(ser_dir / f"{row['run_id']}.npz", centers=centers, **series)
            rec = dict(row, T_max=t_max, t_spec=tspec, dt=rv.DT, M=rv.DEFAULT_M, substeps=rv.DEFAULT_SUBSTEPS,
                       threshold=rv.THRESHOLD, persistence_width=rv.PERSISTENCE_WIDTH, running_width=rv.RUNNING_WIDTH,
                       orbit_norms={str(m): nab[m] for m in range(1, MMAX + 1)}, norm_max_deviation=normdev,
                       twa_variance_check=tw['var_check'], qfi_twa_t0=float(tw['qfi'][0]), ranks=per_m,
                       series_file=f"series/{row['run_id']}.npz",
                       completed_utc=datetime.now(timezone.utc).isoformat(), **env)
            rec_path.write_text(json.dumps(rec, indent=2, sort_keys=True), encoding='utf-8')
            summary = ' '.join(f"m{m}:{per_m[str(m)]['censor_type'][0]}"
                               f"{'' if per_m[str(m)].get('t_b') is None else '=%.2f' % per_m[str(m)]['t_b']}"
                               for m in range(1, MMAX + 1))
            print(f"{row['run_id']}: N={N} rep={rep} {summary}", flush=True)

    recs = [json.loads(p.read_text()) for p in sorted(rec_dir.glob('MQG9T-*.json'))]
    cols = ['run_id', 'N', 'replicate', 'seed', 'm', 'censor_type', 't_b', 'lower_bound', 'upper_bound',
            'max_running_excess', 't_at_max', 'T_max', 'completed_utc']
    with (out / 'mqg_test9T_returntimes.csv').open('w', newline='', encoding='utf-8') as f:
        w = csv.DictWriter(f, fieldnames=cols)
        w.writeheader()
        for r in recs:
            for m in range(1, MMAX + 1):
                d = r['ranks'][str(m)]
                w.writerow(dict(run_id=r['run_id'], N=r['N'], replicate=r['replicate'], seed=r['seed'], m=m,
                                censor_type=d.get('censor_type'), t_b=d.get('t_b'), lower_bound=d.get('lower_bound'),
                                upper_bound=d.get('upper_bound'), max_running_excess=d['max_running_excess'],
                                t_at_max=d['t_at_max'], T_max=r['T_max'], completed_utc=r['completed_utc']))
    (out / 'mqg_test9T_status.json').write_text(json.dumps(dict(
        rows_completed=len(recs), rows_required=len(rows), python=sys.version, platform=platform.platform(),
        updated_utc=datetime.now(timezone.utc).isoformat(), **env), indent=2), encoding='utf-8')
    print(f'MQG test 9T rows completed: {len(recs)}/{len(rows)}. Not scored here.')


if __name__ == '__main__':
    main()
