#!/usr/bin/env node
/* Offline gate for the-average-of-a-million-is-one.
 * Run: node research/the-average-of-a-million-is-one/verify-the-average-of-a-million-is-one.mjs
 * Node 22, no dependencies, no network. The full-size section takes about two minutes.
 */
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';

import * as ref from '../../public/strata/the-average-of-a-million-is-one/reference.js';
import * as P from '../../public/strata/the-average-of-a-million-is-one/plan.js';

const SLUG = 'the-average-of-a-million-is-one';
const DIR = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(DIR, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', SLUG, 'index.html');
const WASM = path.join(ROOT, 'public', 'strata', SLUG, 'engine.wasm');

let n = 0, fails = 0;
const ok = (cond, msg) => {
  n++;
  console.log(`${cond ? 'PASS' : 'FAIL'} ${String(n).padStart(3)}  ${msg}`);
  if (!cond) fails++;
};
const skip = (msg) => console.log(`SKIP  ---  ${msg}`);

/* ---------- load the engine ---------- */

const bytes = fs.readFileSync(WASM);
const mod = await WebAssembly.compile(bytes);
const inst = new WebAssembly.Instance(mod, {});
const x = inst.exports;
for (const need of ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'memory']) {
  ok(need in x, `engine exports ${need}`);
}

/* ---------- hash ---------- */

let manifest = null;
try {
  manifest = await import(`../../public/strata/${SLUG}/manifest.js`);
} catch { /* handled below */ }
const digest = crypto.createHash('sha256').update(bytes).digest('hex');
if (manifest && manifest.WASM_SHA256) {
  ok(digest === manifest.WASM_SHA256.toLowerCase(), `sha256(engine.wasm) == manifest.WASM_SHA256 (${digest.slice(0, 16)}...)`);
} else {
  ok(false, 'manifest.js with WASM_SHA256 is present and importable');
}

/* ---------- reproducible build, with an honest skip ---------- */

try {
  const ver = execFileSync('clang', ['--version'], { encoding: 'utf8' });
  const pinned = manifest && manifest.CLANG ? String(manifest.CLANG) : null;
  if (pinned && ver.includes(pinned)) {
    const out = path.join(DIR, '.rebuild.wasm');
    execFileSync('bash', [path.join(ROOT, 'research/_ox3/lib/build-wasm.sh'), path.join(ROOT, 'public/strata', SLUG, 'engine.c'), out]);
    const same = Buffer.compare(fs.readFileSync(out), bytes) === 0;
    fs.unlinkSync(out);
    ok(same, 'rebuild of engine.c is byte-identical to the committed engine.wasm');
  } else {
    skip(`reproducible build (clang ${ver.split('\n')[0]} != pinned ${pinned})`);
  }
} catch (e) {
  skip(`reproducible build (clang or build script unavailable: ${String(e.message).slice(0, 80)})`);
}

/* ---------- a local runner mirroring the kit's inline loop ---------- */

function makeInst() {
  const i = new WebAssembly.Instance(mod, {});
  const e = i.exports;
  return {
    init(p0, p1) { if (e.aw_reset) e.aw_reset(); e.aw_init(p0 >>> 0, p1 >>> 0); },
    chunk(r, idx, nc) {
      const ops = BigInt.asUintN(64, e.aw_chunk(r >>> 0, idx >>> 0, nc >>> 0));
      const len = e.aw_out_len() >>> 0;
      const out = new Uint8Array(e.memory.buffer, e.aw_out() >>> 0, len).slice();
      return { out, ops };
    },
  };
}

async function runBoth(cfg, chunks) {
  const sub = { ...P.plan, ...cfg, chunks };
  const wi = makeInst();
  let accW = P.initial();
  wi.init(sub.p0, sub.p1);
  let opsW = 0n;
  for (let i = 0; i < chunks; i++) {
    const c = wi.chunk(0, i, chunks);
    opsW += BigInt(c.ops);
    P.reduce(accW, new DataView(c.out.buffer));
  }
  ref.init(sub.p0, sub.p1);
  let accR = P.initial();
  for (let i = 0; i < chunks; i++) {
    const c = ref.chunk(0, i, chunks);
    P.reduce(accR, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength));
  }
  return { accW, accR, fw: P.fingerprint(accW), fr: P.fingerprint(accR), opsW };
}

/* ---------- battery ---------- */

let prevFps = [];
for (const row of P.battery) {
  const { fw, fr } = await runBoth(row, row.chunks);
  ok(fw === fr, `battery "${row.label}": engine and reference fingerprints agree`);
  prevFps.push(fw);
}
// The battery must reach more than one instance, not have pairwise-different rows: the
// full-size check recomputes the same instance under a different decomposition, so where
// that row sits in the battery it agrees by construction. Coincidences are reported.
ok(new Set(prevFps).size >= 2, `battery exercises ${new Set(prevFps).size} distinct instance(s) across ${prevFps.length} rows` + (new Set(prevFps).size < prevFps.length ? `, ${prevFps.length - new Set(prevFps).size} agreeing across a different decomposition` : ''));

/* ---------- control ---------- */

{
  const broken = P.breakReference(P.plan.reference);
  ok(broken !== P.plan.reference, 'breakReference returns a different object');
  let caught = 0;
  for (const row of P.battery) {
    const sub = { ...P.plan, ...row, chunks: row.chunks };
    const wi = makeInst();
    let accW = P.initial();
    wi.init(sub.p0, sub.p1);
    for (let i = 0; i < row.chunks; i++) P.reduce(accW, new DataView(wi.chunk(0, i, row.chunks).out.buffer));
    broken.init(sub.p0, sub.p1);
    let accB = P.initial();
    for (let i = 0; i < row.chunks; i++) {
      const c = broken.chunk(0, i, row.chunks);
      P.reduce(accB, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength));
    }
    if (P.fingerprint(accW) !== P.fingerprint(accB)) caught++;
  }
  P.unbreakReference();
  ok(caught >= 1, `control: the broken reference is caught on ${caught}/${P.battery.length} battery rows`);
}

/* ---------- full size: the CDF arm, two decompositions, closed-form check ---------- */

console.log('# full-size section, about two minutes on one core');

const cdfRuns = P.FULL_RUNS.filter((r) => r.key.startsWith('cdf'));
const accByChunk = {};
for (const r of cdfRuns) {
  const t0 = Date.now();
  const { accW, fw } = await runBoth(r.cfg, r.chunks).then((o) => ({ accW: o.accW, fw: o.fw }));
  accByChunk[r.key] = { acc: accW, fw };
  const N = accW.below + accW.above + accW.lin.reduce((a, b) => a + b, 0);
  const nn = Number(r.cfg.p1);
  const D = P.ksUpper(accW, P.cauchyCdf);
  const crit = P.ksCrit(N);
  ok(D < crit, `KS(empirical mean CDF, exact Cauchy) at n=${nn}: D=${D.toFixed(5)} < crit=${crit.toFixed(5)} (N=${N}, ${((Date.now() - t0) / 1000).toFixed(1)}s)`);
}
{
  const a = accByChunk['cdf1e6'].fw;
  const { fw: b } = await runBoth(P.DECOMP_RUN.cfg, P.DECOMP_RUN.chunks);
  ok(a === b, `second decomposition (chunks ${P.DECOMP_RUN.chunks} vs 80) gives a byte-identical accumulator at n=1000000`);
}

/* ---------- full size: the bootstrap arm ---------- */

{
  const bootRun = P.FULL_RUNS.find((r) => r.key === 'boot');
  const { accW } = await runBoth(bootRun.cfg, bootRun.chunks);
  const cov = accW.covHit / accW.covTry;
  const sub = accW.subHit / accW.subTry;
  console.log(`# measured: percentile-bootstrap coverage ${cov.toFixed(4)}, subsampling coverage ${sub.toFixed(4)} (${accW.covTry} experiments)`);
  ok(cov < 0.85, `percentile-bootstrap coverage at n=100 Cauchy is far below nominal: ${cov.toFixed(4)} < 0.85`);
  ok(sub >= cov, `subsampling at b=10 does no worse than the percentile bootstrap: ${sub.toFixed(4)} >= ${cov.toFixed(4)}`);
  ok(accW.maxrm < 1e8, `cleanest resample mean stays ordinary: max=${accW.maxrm.toExponential(2)} < 1e8`);

  for (const pr of P.PLANTED_RUNS) {
    const { accW: pa } = await runBoth(pr.cfg, pr.chunks);
    if (pr.key === 'gauss') {
      const c = pa.covHit / pa.covTry;
      ok(c >= 0.84 && c <= 0.96, `planted gaussian stream: coverage returns to nominal, ${c.toFixed(4)} in [0.84, 0.96]`);
    } else {
      const c = pa.covHit / pa.covTry;
      // The original assertion predicted collapse (c < 0.05) and the arithmetic
      // says otherwise: a resample of 100 misses the planted index with
      // probability (99/100)^100 = 36.6%, so the 5th percentile of 2000
      // resample means sits deep inside the outlier-free block while the 95th
      // is dragged past 1e8 (assertion 28). The interval therefore EXPLODES
      // and keeps covering zero: coverage stays near the clean stream's, and
      // what collapses is informativeness, not coverage. Assert the corrected
      // prediction, banded generously; collapse was the spec's guess.
      ok(c > 0.5 && c < 0.95,
        `planted outlier stream: coverage does NOT collapse (interval explodes instead), ${c.toFixed(4)} in (0.5, 0.95)`);
      ok(pa.maxrm > 1e8, `planted outlier reaches the resamples: max resample mean ${pa.maxrm.toExponential(2)} > 1e8`);
    }
  }
}

/* ---------- full size: the scaling arm ---------- */

for (const a of P.ALPHAS) {
  const run = P.FULL_RUNS.find((r) => r.key === 'scal' + a);
  const { accW } = await runBoth(run.cfg, run.chunks);
  const slope = P.slopeFit(accW);
  const exact = 1 / a - 1;
  ok(Math.abs(slope - exact) <= 0.15, `scaling exponent at alpha=${a}: fitted ${slope.toFixed(3)} vs exact ${exact.toFixed(3)}`);
}
for (const sr of P.SOLO_RUNS) {
  const { accW } = await runBoth(sr.cfg, sr.chunks);
  const N = accW.below + accW.above + accW.lin.reduce((a, b) => a + b, 0);
  const alpha = sr.cfg.p1 / 1024;
  const cdf = alpha === 1 ? P.cauchyCdf : (xx) => P.normCdf(xx / Math.sqrt(2 / 10));
  const D = P.ksUpper(accW, cdf);
  const crit = P.ksCrit(N);
  ok(D < crit, `cross-method: CMS alpha=${alpha} matches the closed form, D=${D.toFixed(5)} < crit=${crit.toFixed(5)}`);
}

/* ---------- the page states these fixed facts ---------- */

{
  const html = fs.readFileSync(PAGE, 'utf8');
  for (const fact of ['n = 100', 'B = 2000', 'b = 10', 'R = 2000', '16000', '2500', '50000', '200000']) {
    ok(html.includes(fact), `page states the fixed constant "${fact}"`);
  }
}

/* ---------- negative controls on the verifier itself ---------- */

{
  const flipped = Buffer.from(bytes);
  flipped[100] ^= 0xff;
  const d2 = crypto.createHash('sha256').update(flipped).digest('hex');
  ok(d2 !== digest, 'CONTROL: flipping one wasm byte changes the hash, so assertion 002 has power');
}
{
  const { accW } = await runBoth(P.battery[0], P.battery[0].chunks);
  const tampered = P.initial();
  const dv = new DataView((await (async () => {
    const wi = makeInst(); wi.init(P.battery[0].p0, P.battery[0].p1);
    const c = wi.chunk(0, 0, P.battery[0].chunks);
    return c.out.buffer;
  })()));
  P.reduce(tampered, dv);
  tampered.lin[7] += 1;                       // a dropped or doubled bin must show
  ok(P.fingerprint(tampered) !== P.fingerprint(accW), 'CONTROL: a one-count tamper in the accumulator changes the fingerprint, so assertion 004 has power');
}

console.log(`
${n - fails}/${n} checks passed${fails ? `, ${fails} FAILED` : ''}`);
process.exit(fails ? 1 : 0);
