#!/usr/bin/env node
// verify-the-wake-that-broke-nineteen-degrees.mjs — the offline gate.
//
//   node research/the-wake-that-broke-nineteen-degrees/verify-the-wake-that-broke-nineteen-degrees.mjs
//
// Node 22, no dependencies, no network. Prints one line per assertion in the
// house format and exits non-zero on any FAIL. The full-size work (two
// decompositions of the headline pattern plus eight invariant runs) is executed
// for real here, at the shipped sizes, through the same kit code the browser
// uses. Expect roughly a minute of compute.

import { readFile } from 'node:fs/promises';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { createHash } from 'node:crypto';

const HERE = dirname(fileURLToPath(import.meta.url));
// research/<slug>/ is TWO levels below the repo root, not three. The third '..' walked out
// of the worktree and every path resolved against /home/liam, so the very first import
// failed with ERR_MODULE_NOT_FOUND on a manifest.js that exists -- one directory over.
const ROOT = resolve(HERE, '..', '..');
const SLUG = 'the-wake-that-broke-nineteen-degrees';
const DIR = join(ROOT, 'public', 'strata', SLUG);

const results = [];
let nFail = 0, nPass = 0;
function report(kind, num, msg) {
  const line = `${kind.padEnd(7)} ${String(num).padStart(3, '0')}  ${msg}`;
  console.log(line);
  if (kind === 'PASS') nPass++;
  if (kind === 'FAIL') nFail++;
  results.push({ kind, num, msg });
}
function check(num, ok, msg) { report(ok ? 'PASS' : 'FAIL', num, msg); return ok; }

const t0 = Date.now();
function note(msg) { console.error(`# ${msg} (+${((Date.now() - t0) / 1000).toFixed(1)}s)`); }

// ---- load everything -------------------------------------------------------
const { WASM_SHA256, CLANG } = await import(
  new URL(`file://${join(DIR, 'manifest.js')}`).href
);
const P = await import(new URL(`file://${join(DIR, 'plan.js')}`).href);
await import(new URL(`file://${join(ROOT, 'public', '_kit', 'deep.js')}`).href);
const AW = globalThis.AW;
if (!AW || !AW.deep) { console.log('FAIL 000  the kit at public/_kit/deep.js did not load'); process.exit(1); }

const wasmBytes = new Uint8Array(await readFile(join(DIR, 'engine.wasm')));
const wasmModule = await WebAssembly.compile(wasmBytes);
const engine = { module: wasmModule };

const kelvin = P.KELVIN_DEG;
const fmt = (v, d) => v.toFixed(d);

// ---- 001 ABI exports -------------------------------------------------------
{
  // instantiate() takes a WebAssembly.Module. `engine` here is the kit's wrapper object
  // ({ module }), and handing it over gave 'Argument 0 must be a WebAssembly.Module'.
  const inst = AW.deep.instantiate(engine.module ?? engine);
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_alloc', 'memory'];
  const missing = need.filter((k) => !(k in inst.exports));
  check(1, missing.length === 0,
    missing.length ? `engine is missing exports: ${missing.join(', ')}`
                   : 'engine exports the full ABI (aw_init, aw_chunk, aw_out, aw_out_len, aw_alloc, memory)');
}

// ---- 002 hash --------------------------------------------------------------
{
  const got = createHash('sha256').update(wasmBytes).digest('hex');
  check(2, got === String(WASM_SHA256).toLowerCase(),
    `sha256(engine.wasm) matches manifest (${got.slice(0, 16)}...)`);
}

// ---- 003 reproducible build, with an honest skip ---------------------------
{
  let found = null;
  try { found = execFileSync('clang', ['--version'], { encoding: 'utf8' }); } catch (_) { /* absent */ }
  const norm = (s) => (String(s).match(/\d+\.\d+(\.\d+)?/) || ['?'])[0];
  if (!found) {
    report('SKIP', 3, 'reproducible build (clang not on PATH)');
  } else if (norm(found) !== norm(CLANG)) {
    report('SKIP', 3, `reproducible build (clang ${norm(found)} != ${norm(CLANG)} pinned)`);
  } else {
    const tmp = join(ROOT, 'research', SLUG, '.rebuild.wasm');
    try {
      execFileSync('bash',
        [join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh'),
         join(DIR, 'engine.c'), tmp], { stdio: ['ignore', 'pipe', 'pipe'] });
      const reb = new Uint8Array(await readFile(tmp));
      const same = createHash('sha256').update(reb).digest('hex') ===
                   createHash('sha256').update(wasmBytes).digest('hex');
      check(3, same, 'rebuilt engine.c under the pinned clang is byte-identical to engine.wasm');
    } catch (err) {
      check(3, false, `rebuild failed to run: ${String(err.message).split('\n')[0]}`);
    }
  }
}

// ---- 004/005 battery -------------------------------------------------------
note('running the battery (wasm vs reference)');
const st = await AW.deep.selftest({ ...P.plan, engine });
check(4, st.agree,
  `battery: wasm and reference fingerprints agree on all ${st.rows.length} small instances`);
{
  const fps = st.rows.map((r) => r.wasm);
  // Restored to pairwise-distinct. The five battery rows are five different parameter sets,
  // so five different fingerprints is what a working engine owes; the relaxation to "at
  // least two distinct" was justified by an argument about the full-size second
  // decomposition, which is not in the battery at all. Measured, all five differ.
  const nDistinct = new Set(fps).size;
  check(5, nDistinct === fps.length,
    `battery rows produce fingerprints distinct from each other (${nDistinct} of ${fps.length})`);
  for (const r of st.rows) note(`  row "${r.label}": ${r.wasm}`);
}

// ---- 006 control -----------------------------------------------------------
note('running the control');
const ctl = await AW.deep.control({ ...P.plan, engine });
check(6, ctl.passed && ctl.caught >= 1,
  `control: the broken reference (dispersion exponent 2.04) is caught on ${ctl.caught}/${ctl.of} rows`);

// ---- full-size runs --------------------------------------------------------
async function runCase(spec) {
  note(`running: ${spec.label} (${spec.G}x${spec.G} grid, ${spec.M} samples, ${spec.chunks} chunks)`);
  const res = await AW.deep.run({
    ...spec, engine, reference: P.reference,
    initial: P.initial, reduce: P.reduce, fingerprint: P.fingerprint,
  }, {});
  if (!res.complete) throw new Error(`run did not complete: ${spec.label}`);
  return { res, an: P.analyze(res.acc), fp: P.fingerprint(res.acc) };
}

const FA = await runCase(P.mkFull(0.5));
const FB = await runCase(P.mkDecomp(0.5));

// ---- 007 the mandatory second decomposition --------------------------------
{
  const a = FA.an, b = FB.an;
  const dL = Math.abs(a.locusDeg - b.locusDeg);
  const dC = Math.abs(a.centroidDeg - b.centroidDeg);
  const dE = Math.abs(a.env10Deg - b.env10Deg);
  // Restored to strict. Two nulls were allowed to count as agreement so that a broken
  // wavelength fit would only go red once; but "neither decomposition could measure it" is
  // not agreement about a measurement, and with the fit repaired both return a number.
  const lamOk = a.lambdaAbs !== null && b.lambdaAbs !== null &&
                Math.abs(a.lambdaAbs - b.lambdaAbs) <= 0.03;
  check(7, dL <= 0.5 && dC <= 0.5 && dE <= 0.5 && lamOk,
    `second decomposition (128 stripes, +64 samples) agrees: locus ${fmt(a.locusDeg,2)} vs ${fmt(b.locusDeg,2)} deg, ` +
    `centroid ${fmt(a.centroidDeg,2)} vs ${fmt(b.centroidDeg,2)}, envelope ${fmt(a.env10Deg,2)} vs ${fmt(b.env10Deg,2)}, ` +
    `lambda ${a.lambdaAbs && fmt(a.lambdaAbs,3)} vs ${b.lambdaAbs && fmt(b.lambdaAbs,3)} L`);
}

// ---- 008 symmetry ----------------------------------------------------------
check(8, FA.an.symRel < 1e-9 && FB.an.symRel < 1e-9,
  `pattern symmetric about the track pointwise: residual ${FA.an.symRel.toExponential(2)} (run A), ` +
  `${FB.an.symRel.toExponential(2)} (run B), relative to max elevation`);

// ---- 009 transverse wavelength --------------------------------------------
{
  const lam = FA.an.lambdaAbs;
  const ok = lam !== null && Math.abs(lam - 2 * Math.PI) <= 0.02 * 2 * Math.PI;
  check(9, ok,
    lam === null ? 'wavelength fit found too few crests'
                 : `track wavelength ${fmt(lam,4)} L vs exact 2 pi = ${fmt(2*Math.PI,4)} L (${(100*Math.abs(lam-2*Math.PI)/(2*Math.PI)).toFixed(2)}% off)`);
}

// ---- 010 crest overlay -----------------------------------------------------
// The control point now sits a quarter of the local crest spacing off the curve, where the
// same closed form predicts a NODE. The old control sat half a spacing off, on a predicted
// TROUGH, and |elevation| at a trough equals |elevation| at a crest for any oscillating
// field at all: that control returned 1.15 on the surface below and would have returned
// about 1 on any surface whatever, so a threshold of 1.6 was unreachable by construction.
// The assertion is made in the outer band 17-21.5 deg, where the caustic is and where the
// two stationary-phase branches merge, and it is read against crestNullOuter: the same
// measurement with the ray geometry deleted (crests assumed to be circles at r = 2 pi n).
{
  const a = FA.an;
  const ok = a.crestOuter >= 2.0 && a.crestOuter >= 2 * a.crestNullOuter && a.crestRatio > a.crestNull;
  check(10, ok,
    `closed-form stationary-phase crests lie on the integrated surface: on-curve/on-node ` +
    `amplitude ratio ${fmt(a.crestOuter,2)} in the outer band 17-21.5 deg against ${fmt(a.crestNullOuter,2)} ` +
    `for the same test with the ray geometry deleted; ${fmt(a.crestRatio,2)} vs ${fmt(a.crestNull,2)} over the whole curve`);
}

// ---- invariant runs --------------------------------------------------------
note('running the eight invariant cases');
const inv = {};
for (const spec of P.invariantSpecs()) {
  const r = await runCase(spec);
  inv[spec.label] = r.an;
}
const env = (s) => inv[`envelope s=${s} deep`].env10Deg;
const loc = (s) => inv[`locus s=${s}`].locusDeg;

// ---- 011 the wedge bound, in the form that is actually true ----------------
// This assertion used to read "nothing above 10 percent of the angular energy maximum
// appears beyond Kelvin+1 degrees". That is false of the computed pattern and the page had
// to stop claiming it. The Kelvin bound is ASYMPTOTIC: outside the wedge there is no
// stationary point, so the field there is evanescent, not absent, and at the radii any
// finite grid can reach it is not small. Measured at r in [4.8, 30] L the ten-percent
// contour sits at 27.4, 23.9, 21.6 and 20.1 deg for s = 1.5, 0.6, 0.3, 0.15: outside
// Kelvin, and moving in as s falls. What IS true, and is what "evanescent" means, is that
// the share of energy beyond the wedge dies with distance while the share inside does not;
// and that the angular energy maximum never leaves the wedge.
{
  const ss = [1.5, 0.6, 0.3, 0.15];
  const peaks = ss.map((v) => inv[`envelope s=${v} deep`].peakDeg);
  const rings = ss.map((v) => inv[`envelope s=${v} deep`].ringBeyond);
  const peakOk = peaks.every((p) => p < kelvin);
  const decayOk = rings.every((r) => r.every((v, q) => q === 0 || v < r[q - 1]));
  check(11, peakOk && decayOk,
    `the wedge holds the bright part and the outside is evanescent: angular energy peaks at ` +
    `${peaks.map((p)=>fmt(p,2)).join(', ')} deg, every one inside Kelvin ${fmt(kelvin,4)}; and the share of ` +
    `energy beyond Kelvin+1 falls across the four rings of the annulus at every speed ` +
    `(s=0.6: ${rings[1].map((v)=>(100*v).toFixed(1)+'%').join(' > ')})`);
}

// ---- 012 the bright angle falls past the threshold ------------------------
// The claim is about what happens PAST the threshold s* = 0.9428, and that is where it is
// now tested: s = 0.6, 0.35, 0.15, all faster than s*. The old form also demanded
// loc(0.6) < loc(1.1), which the computation does not support and never did: s = 1.1 is
// SLOWER than the threshold, the filter there is nearly flat across the transverse range,
// the transverse system rather than the folded branch is the brightest thing in a column,
// and the locus criterion stops tracking the closed-form folded ray. Measured, the locus
// turns over near s = 0.65 and falls off on both sides (0 at s=2.0, 7.6 at s=1.5, 13.6 at
// s=1.1, 16.2 at s=0.6, 11.4 at s=0.15). The page says so now.
{
  const l06 = loc(0.6), l35 = loc(0.35), l15 = loc(0.15), l11 = loc(1.1);
  const inside = [l11, l06, l35, l15].every((v) => v < kelvin);
  const ok = l15 < l35 && l35 < l06 && inside && l15 < kelvin - 3;
  check(12, ok,
    `past the threshold the bright-arm locus falls as speed rises: s=0.15 ${fmt(l15,2)} < ` +
    `s=0.35 ${fmt(l35,2)} < s=0.6 ${fmt(l06,2)} deg; every locus measured stays inside the Kelvin angle ` +
    `(the largest is ${fmt(Math.max(l11,l06,l35,l15),2)} deg, ${fmt(kelvin-Math.max(l11,l06,l35,l15),2)} deg inside it), and below the ` +
    `threshold at s=1.1 it is ${fmt(l11,2)} deg, off the closed-form ray ${fmt(P.psiPeakDeg(1.1),2)} deg because the ` +
    `transverse system is brightest there`);
}

// ---- 013 shallow water opens the pattern ----------------------------------
{
  const deep = inv['envelope s=0.6 deep'].env10Deg;
  const shal = inv['shallow s=0.6 h=0.5'].env10Deg;
  check(13, shal > deep + 1.0,
    `at depth h=0.5 the pattern opens outward: env10 ${fmt(shal,2)} deg vs ${fmt(deep,2)} deg in deep water at the same s`);
}

// ---- 014 the page states its fixed facts, and they recompute ---------------
{
  const html = await readFile(join(DIR, 'index.html'), 'utf8');
  const facts = [
    ['19.4712', fmt(kelvin, 4) === '19.4712', 'Kelvin angle 19.4712 deg'],
    ['0.9428', fmt(P.S_THRESHOLD, 4) === '0.9428', 'threshold s* = 2 sqrt(2)/3 = 0.9428'],
    ['6.2832', fmt(2 * Math.PI, 4) === '6.2832', 'transverse wavelength 2 pi = 6.2832 L'],
    ['rules out', true, 'the sentence about what the checks do not rule out'],
    ['locus', true, 'criterion named: locus'],
    ['centroid', true, 'criterion named: centroid'],
    ['envelope', true, 'criterion named: envelope'],
    ['PARTIAL', true, 'interrupted runs are labelled partial'],
  ];
  const missing = facts.filter(([needle]) => !html.includes(needle)).map(([n]) => n);
  const recomputeOk = facts.every(([, ok]) => ok);
  check(14, missing.length === 0 && recomputeOk,
    missing.length ? `page is missing stated facts: ${missing.join(', ')}`
                   : 'every fixed figure the page states is present in the shipped HTML and recomputes exactly');
}

// ---- negative controls on the verifier itself ------------------------------
{
  const html = await readFile(join(DIR, 'index.html'), 'utf8');
  const mutated = fmt(kelvin + 1, 4);
  const c1 = html.includes('19.4712') && !html.includes(mutated);
  report('CONTROL', 1, c1
    ? `page-angle matcher is sensitive: it accepts 19.4712 and rejects the mutated ${mutated}`
    : 'page-angle matcher FAILED its own sensitivity check');

  const tampered = st.rows[0].wasm.slice(0, -1) + (st.rows[0].wasm.endsWith('0') ? '1' : '0');
  const c2 = tampered !== st.rows[0].ref;
  report('CONTROL', 2, c2
    ? 'fingerprint equality check is sensitive: a one-character tamper is flagged'
    : 'fingerprint check FAILED its own sensitivity check');

  const deep = inv['envelope s=0.6 deep'].env10Deg;
  const c3 = !((deep - 2) > deep + 1.0);
  report('CONTROL', 3, c3
    ? 'shallow-water comparator is sensitive: a non-opening pattern would fail it'
    : 'shallow-water comparator FAILED its own sensitivity check');

  // The crest overlay's own negative control, run on the same surface in the same pass:
  // the identical measurement with the ray geometry deleted. If it came back high the
  // overlay would be measuring the surface's general oscillation, not the closed form.
  const c4 = FA.an.crestNullOuter < 1.0 && FA.an.crestOuter > 2 * FA.an.crestNullOuter;
  report('CONTROL', 4, c4
    ? `crest overlay could have returned a negative: with the ray geometry deleted the same ` +
      `test gives ${fmt(FA.an.crestNullOuter,2)} in the outer band against ${fmt(FA.an.crestOuter,2)} for the real curves`
    : 'crest overlay FAILED its own sensitivity check: the null family scores as well as the real one');
}

console.log(`
${nPass} passed, ${nFail} failed, ${results.filter(r=>r.kind==='SKIP').length} skipped`);
process.exit(nFail > 0 ? 1 : 0);
