#!/usr/bin/env node
// Offline gate for the-region-where-the-double-is-wrong.
// Run from a fresh checkout:  node research/the-region-where-the-double-is-wrong/verify-the-region-where-the-double-is-wrong.mjs
// Node 22, no dependencies, no network.

import { readFileSync, existsSync, mkdtempSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const DIR = path.join(ROOT, 'public', 'strata', 'the-region-where-the-double-is-wrong');

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

const WASM_PATH = path.join(DIR, 'engine.wasm');
const wasmBytes = readFileSync(WASM_PATH);

// ---------------------------------------------------------------- 001 load + ABI
const mod = new WebAssembly.Module(wasmBytes);
const inst = new WebAssembly.Instance(mod, {});
const x = inst.exports;
const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'memory'];
P(need.every((k) => k in x), `engine.wasm instantiates and exports ${need.join(', ')}`);

// ---------------------------------------------------------------- 002 hash
const manifest = await import(pathToFileURL(path.join(DIR, 'manifest.js')));
const digest = createHash('sha256').update(wasmBytes).digest('hex');
P(digest === manifest.WASM_SHA256.toLowerCase(),
  `sha256(engine.wasm) equals manifest.WASM_SHA256 (${digest.slice(0, 16)}...)`);

// ---------------------------------------------------------------- 003 reproducible build, honest skip
(function reproducible() {
  let found = null;
  try {
    const r = spawnSync('clang', ['--version'], { encoding: 'utf8' });
    if (r.status === 0) found = r.stdout.split('\n')[0].trim();
  } catch (_) {}
  const pinned = manifest.CLANG || '';
  if (!found || !pinned || !found.includes(pinned)) {
    SKIP(`reproducible build (clang ${found ? found.split(' ').slice(-1)[0] : 'absent'} != pinned ${pinned || 'none'})`);
    return;
  }
  const script = path.join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh');
  if (!existsSync(script)) {
    SKIP(`reproducible build (build script research/_ox3/lib/build-wasm.sh not present in this checkout)`);
    return;
  }
  const outDir = mkdtempSync(path.join(tmpdir(), 'awbuild-'));
  const outFile = path.join(outDir, 'engine.wasm');
  const r = spawnSync('bash', [script, path.join(DIR, 'engine.c'), outFile], { encoding: 'utf8' });
  if (r.status !== 0 || !existsSync(outFile)) {
    SKIP(`reproducible build (build script exited ${r.status})`);
    return;
  }
  const rebuilt = readFileSync(outFile);
  P(rebuilt.equals(wasmBytes), 'rebuilt engine.c is byte-identical to engine.wasm');
})();

// ---------------------------------------------------------------- runners
const plan = (await import(pathToFileURL(path.join(DIR, 'plan.js')))).plan;
const reference = await import(pathToFileURL(path.join(DIR, 'reference.js')));

function makeInst() {
  const i = new WebAssembly.Instance(mod, {});
  const e = i.exports;
  return {
    chunk(r, idx, nn) {
      const ops = e.aw_chunk(r, idx, nn);
      const len = e.aw_out_len();
      const out = new Uint8Array(e.memory.buffer, e.aw_out(), len).slice();
      return { out, ops };
    },
    init: (p0, p1) => e.aw_init(p0 >>> 0, p1 >>> 0),
  };
}
function ctxFor(row) { return Object.assign({}, plan, row); }
function runEngine(row) {
  const ctx = ctxFor(row);
  const inst2 = makeInst();
  inst2.init(ctx.p0, ctx.p1);
  const acc = ctx.initial.call(ctx);
  for (let i = 0; i < ctx.chunks; i++) {
    const c = inst2.chunk(0, i, ctx.chunks);
    ctx.reduce.call(ctx, acc, new DataView(c.out.buffer), i, 0);
  }
  return acc;
}
function runRef(row, refImpl) {
  const ctx = ctxFor(row);
  const impl = refImpl || reference;
  impl.init(ctx.p0, ctx.p1);
  const acc = ctx.initial.call(ctx);
  for (let i = 0; i < ctx.chunks; i++) {
    const c = impl.chunk(0, i, ctx.chunks);
    ctx.reduce.call(ctx, acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, 0);
  }
  return acc;
}

// ---------------------------------------------------------------- 004/005 battery
const fps = [];
let allAgree = true;
for (const row of plan.battery) {
  const ef = plan.fingerprint(runEngine(row));
  const rf = plan.fingerprint(runRef(row));
  if (ef !== rf) allAgree = false;
  P(ef === rf, `battery "${row.label}": engine and reference fingerprints agree`);
  fps.push([row.label, ef]);
}
P(allAgree, 'every battery row agrees (engine vs reference, summary)');

{
  let dup = '';
  for (let i = 0; i < fps.length && !dup; i++) {
    for (let j = i + 1; j < fps.length; j++) {
      if (fps[i][1] === fps[j][1]) { dup = `${fps[i][0]} vs ${fps[j][0]}`; break; }
    }
  }
  P(!dup, `battery rows are pairwise distinct${dup ? ` (${dup} collide)` : ''}`);
}

// ---------------------------------------------------------------- 005 control
const broken = plan.breakReference(reference);
P(broken && broken !== reference && typeof broken.init === 'function' && typeof broken.chunk === 'function',
  'breakReference returns a different implementation object');
{
  let caught = 0;
  for (const row of plan.battery) {
    const ef = plan.fingerprint(runEngine(row));
    const bf = plan.fingerprint(runRef(row, broken));
    if (ef !== bf) caught++;
  }
  P(caught > 0,
    `broken reference (coefficient 121 -> 122) caught on ${caught}/${plan.battery.length} battery rows`);
}

// ---------------------------------------------------------- exact-side helpers
const MASK64 = (1n << 64n) - 1n;
const _f64 = new Float64Array(1);
const _u64 = new BigUint64Array(_f64.buffer);
const bitsOf = (v) => { _f64[0] = v; return _u64[0]; };
const toD = (bn) => { _u64[0] = bn; return _f64[0]; };

// Direct expansion over BigInt, the same contract reference.js implements,
// restated here so the planted values and the centre value are checked
// against a third independent writing of the cleared rule.
function gBig(x, y, c121) {
  const X = BigInt(x), Y = BigInt(y);
  const y2 = Y * Y, y4 = y2 * y2, y6 = y4 * y2, y7 = y6 * Y, y9 = y7 * y2;
  const x2 = X * X;
  const inner = 11n * x2 * y2 - y6 - BigInt(c121) * y4 - 2n;
  return 1335n * y7 + 4n * x2 * Y * inner + 22n * y9 + 2n * X;
}

function ratioDecimal(num, den, digits) {
  const neg = num < 0n;
  const a = neg ? -num : num;
  const ip = a / den;
  let frac = '';
  if (digits > 0) {
    const r = (a % den) * 10n ** BigInt(digits);
    frac = (r / den).toString().padStart(digits, '0').replace(/0+$/, '');
  }
  return (neg ? '-' : '') + ip.toString() + (frac ? '.' + frac : '');
}

// ---------------------------------------------------------------- 006 planted points
const PLANTED = [[0, 2, 22768], [4, 2, 2001], [8, 2, 74866], [12, 2, 646867]];
for (const [px, py, pf] of PLANTED) {
  const f = gBig(px, py, 121) / BigInt(4 * py);
  P(f === BigInt(pf), `planted point (${px},${py}): exact f rederives to ${pf} from the cleared rule`);
}
{
  const inst2 = makeInst();
  inst2.init(0, 1);
  let okG = true, okD = true, okY = true, okC = true;
  for (let i = 0; i < 4; i++) {
    const c = inst2.chunk(0, i, 4);
    const dv = new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength);
    const [px, py, pf] = PLANTED[i];
    if (dv.getBigUint64(0, true) !== (gBig(px, py, 121) & MASK64)) okG = false;
    if (dv.getBigUint64(8, true) !== bitsOf(pf)) okD = false;
    if (dv.getBigUint64(56, true) !== BigInt(4 * py)) okY = false;
    if (dv.getBigUint64(80, true) !== 1n) okC = false;   // outward verdict: accepted
  }
  P(okG, 'engine mode-1 records carry the exact planted g (low 64 bits)');
  P(okD, 'engine mode-1 records: the unmodified double path lands exactly on each planted integer');
  P(okY, 'engine mode-1 records carry 4y = 8');
  P(okC, 'engine mode-1 records: the containment test accepts all four outward intervals');
}

// -------- EVERY named arrangement, against the exact value, not against its twin
//
// The battery compares the engine with the reference. Both are transcriptions
// of the same written arrangements by the same hand, so a misread of the
// ALGEBRA of an arrangement is invisible to it: the two agree on the wrong
// polynomial. The planted points are the instrument that does not read the
// spec. At y = 2 with x a multiple of 4 every intermediate of every
// arrangement is a small exactly-representable number and every operation on
// it is exact, so an arrangement that really is a regrouping of f must return
// the planted integer EXACTLY. One that is a different polynomial cannot.
// This is what caught the shipped Horner-in-z, which put 11x^4 and -121x^2 in
// the same Horner stage and so evaluated 11x^4 z^2 in place of 11x^4 z.
const ARRW = [[8, 'pinned double'], [16, 'single, widened'], [24, 'double-double hi'],
              [64, 'left-associated double'], [72, 'Horner-in-y^2 double']];
function plantedRecords() {
  const inst2 = makeInst();
  inst2.init(0, 1);
  const recs = [];
  for (let i = 0; i < 4; i++) {
    const c = inst2.chunk(0, i, 4);
    recs.push(new DataView(c.out.buffer.slice(c.out.byteOffset, c.out.byteOffset + c.out.byteLength)));
  }
  return recs;
}
function arrangementComplaints(recs) {
  const bad = [];
  for (let i = 0; i < 4; i++) {
    const dv = recs[i];
    const [px, py, pf] = PLANTED[i];
    for (const [off, nm] of ARRW) {
      const got = toD(dv.getBigUint64(off, true));
      if (got !== pf) bad.push(`(${px},${py}) ${nm}: ${got} instead of ${pf}`);
    }
    if (toD(dv.getBigUint64(32, true)) !== 0) bad.push(`(${px},${py}) double-double lo is not 0`);
    const lo = toD(dv.getBigUint64(40, true)), hi = toD(dv.getBigUint64(48, true));
    if (!(lo <= pf && pf <= hi)) bad.push(`(${px},${py}) outward interval [${lo}, ${hi}] does not contain ${pf}`);
  }
  return bad;
}
{
  const bad = arrangementComplaints(plantedRecords());
  for (const s of bad) INFO(s);
  P(bad.length === 0,
    'every named arrangement lands EXACTLY on the planted integer at all four planted points (an absolute check: the battery compares the two implementations with each other, this compares both against arithmetic)');
}
{
  // Positive control for the assertion above, on the checking path itself: the
  // same comparison, run over records with ONE arrangement word moved by one
  // ulp, must complain. A zero is only evidence if a one could have appeared.
  const recs = plantedRecords();
  recs[2].setBigUint64(72, recs[2].getBigUint64(72, true) + 1n, true);
  CONTROL(arrangementComplaints(recs).length > 0,
    'nudging one arrangement word by one ulp makes the planted-arrangement check complain, so its zero is a measurement and not a blind spot');
}

// ---------------------------------------------------------------- 007 the famous point
{
  const ep = reference.evalPoint(77617, 33096);
  P(ep.g === -109534n, 'exact g(77617,33096) = -109534, that is f = -54767/66192');
  P(ep.sgC === 0, 'the exact sign at the famous point is negative');
  P(ep.dbl < 0 && Math.abs(ep.dbl) > 1.17e21 && Math.abs(ep.dbl) < 1.19e21,
    `the pinned double arrangement measures ${ep.dbl.toExponential(6)} (page says about -1.18e21)`);
  P(ep.cok === 1, 'the outward interval contains the exact value at the famous point');

  const inst2 = makeInst();
  inst2.init(0, 3);
  const c = inst2.chunk(0, 0, 1);
  const dv = new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength);
  const w = [];
  for (let i = 0; i < 10; i++) w.push(dv.getBigUint64(8 * i, true));

  // Word-by-word comparison with named diagnostics. A bare ten-word boolean
  // cannot localize a disagreement; if any word ever differs, the log names
  // the word, what the engine wrote, and what evalPoint reads.
  const names = [
    'low 64 bits of |g|', 'exact sign code', 'pinned double',
    'left-associated double', 'Horner-in-y^2 double', 'single widened',
    'double-double hi', 'double-double lo', 'interval lo', 'interval hi',
  ];
  const expect = [
    109534n, 0n,
    bitsOf(ep.dbl), bitsOf(ep.a2), bitsOf(ep.a3), bitsOf(ep.sgl),
    bitsOf(ep.dd.hi), bitsOf(ep.dd.lo), bitsOf(ep.iv.lo), bitsOf(ep.iv.hi),
  ];
  let bad = -1;
  for (let i = 0; i < 10; i++) if (w[i] !== expect[i]) { bad = i; break; }
  if (bad >= 0) {
    for (let i = 0; i < 10; i++) {
      console.log(`INFO        word ${i} (${names[i]}): engine ${w[i]} reference ${expect[i]} ${w[i] === expect[i] ? 'ok' : 'DIFF'}`);
    }
  }
  P(bad < 0, bad < 0
    ? 'engine mode-3 record matches reference.evalPoint bit for bit, all ten words'
    : `engine mode-3 record DIFFERS at word ${bad} (${names[bad]}): engine ${w[bad]} vs reference ${expect[bad]}`);
}

// ---------------------------------------------------------------- record sizes
{
  const i2 = makeInst();
  i2.init(2, 0);
  P(i2.chunk(0, 0, 1).out.length === 272, 'census record is 272 bytes');
  i2.init(0, 1);
  P(i2.chunk(0, 0, 4).out.length === 88, 'planted record is 88 bytes');
  i2.init(0, 3);
  P(i2.chunk(0, 0, 1).out.length === 80, 'centre record is 80 bytes');
}

// ---------------------------------------------------------- 007b narrowed-rounding control
// The control must demonstrate that the containment test can FAIL. A census
// point is the wrong place to demand that: the width of a census interval is
// dominated by intrinsic round-to-nearest debris from the ~8e36 sites (one
// ulp there is 2^70 ~ 1.18e21), and flipping the nudge direction retracts
// only the deliberate one-ulp pads, not that debris, so an inward census
// interval cannot exclude a value of size O(1) and a mode-2 gate is green
// forever. See the README's window analysis. The control therefore lives at
// the four planted points, where every operation is exact, the interval is a
// degenerate point held open by the pads alone, and the inward interval
// provably inverts. Both directions are required, on the same four points,
// through the same code path: rejection under inward rounding, acceptance
// under outward rounding, so a constant rejector also fails the gate.
{
  // Window probe: one specific census point, both nudge directions, printed
  // on every run so the window claim stays tied to live numbers.
  const PX = 77617, PY = 33096;
  const eo = reference.evalPoint(PX, PY, false);
  const en = reference.evalPoint(PX, PY, true);
  INFO(`narrow-window probe at (${PX}, ${PY}):`);
  INFO(`  exact            f = ${ratioDecimal(eo.g, BigInt(eo.y4), 25)}`);
  INFO(`  outward interval   [${eo.iv.lo.toExponential(12)}, ${eo.iv.hi.toExponential(12)}]  width ${(eo.iv.hi - eo.iv.lo).toExponential(6)}`);
  INFO(`  inward  interval   [${en.iv.lo.toExponential(12)}, ${en.iv.hi.toExponential(12)}]  width ${(en.iv.hi - en.iv.lo).toExponential(6)}`);
  INFO(`  inward contains the exact value: ${en.cok === 1} (expected yes: the surviving width is of order 1e21, the debris it would need to outrun is the same order, see README)`);

  const na = runEngine({ label: 'narrow-census-info', p0: 2, p1: 2, chunks: 2 });
  INFO(`mode-2 inward census at halfwidth 2: containFail = ${na.containFail} (informational; this mode cannot be the red control)`);

  const accIn = runEngine({ label: 'narrow-gate', p0: 0, p1: 4, chunks: 4 });
  const rej = accIn.rows.filter((r) => r.cok === 0n).length;
  P(rej === 4,
    `narrowed-rounding control: inward intervals at the four planted points are rejected ${rej}/4, so the containment test can fail`);

  const accOut = runEngine({ label: 'outward-gate', p0: 0, p1: 1, chunks: 4 });
  const acc = accOut.rows.filter((r) => r.cok === 1n).length;
  P(acc === 4,
    `same containment test accepts all four outward planted intervals (${acc}/4), so it is not a constant rejector`);
}

// ---------------------------------------------------------------- 008 full size
let wrongSign = null;
INFO('full-size check: 16,785,409 points per run, engine only (the BigInt reference cannot reach this size here)');
{
  const t0 = Date.now();
  const fa = runEngine({ label: 'full-a', p0: 2048, p1: 0, chunks: 256 });
  const fb = runEngine({ label: 'full-b', p0: 2048, p1: 0, chunks: 97 });
  P(plan.fingerprint(fa) === plan.fingerprint(fb),
    'full-size: two decompositions (256 strips, 97 strips) give identical fingerprints');
  P(fa.containFail === 0, 'full-size: zero outward-interval containment failures');
  P(fa.crossBad === 0, 'full-size: zero Horner-vs-direct-expansion mismatches');
  INFO(`full-size runs took ${((Date.now() - t0) / 1000).toFixed(1)} s`);

  // The headline measurement, printed so the page's words can be checked
  // against it. Bin b of a block is exactSign*3 + precisionSign, so the
  // off-diagonal bins are the points where that precision has the wrong sign.
  const off = (blk) => { let s = 0; for (let b = 0; b < 9; b++) if (b % 3 !== ((b / 3) | 0)) s += fa.hist[blk + b]; return s; };
  wrongSign = { dbl: off(0), sgl: off(9), dd: off(18) };
  INFO(`MEASURED over 16,785,409 lattice points: wrong-sign points, double = ${wrongSign.dbl}, single = ${wrongSign.sgl}, double-double = ${wrongSign.dd}; single right while double wrong = ${fa.nonMono}; double-double right while double wrong = ${fa.ddRight}`);
  INFO(`exact signs over the census: negative ${fa.hist[0] + fa.hist[1] + fa.hist[2]}, zero ${fa.hist[3] + fa.hist[4] + fa.hist[5]}, positive ${fa.hist[6] + fa.hist[7] + fa.hist[8]}`);
}

// ---------------------------------------------------------------- 009 page facts
const html = readFileSync(path.join(DIR, 'index.html'), 'utf8');
{
  const FACTS = [
    '16,785,409',
    '-54767/66192',
    '22768', '2001', '74866', '646867',
    '77617', '33096',
    '\u00b12048',
    '256 strips, 97 strips',
    'verify-the-region-where-the-double-is-wrong.mjs',
  ];
  for (const f of FACTS) P(html.includes(f), `shipped page states the fixed fact "${f}"`);
  P((2 * 2048 + 1) ** 2 === 16785409,
    'the census size 16,785,409 is (2*2048+1)^2 at the shipped halfwidth 2048');
  P(html.includes('</body>') && html.includes('</html>'), 'shipped page document is closed');

  // The page's words against the census's own answer. Both of these are
  // claims the measurement can refute, and both were on the page once.
  P(!/(huge|enormous|large)\s+positive/i.test(html),
    'the page does not repeat the retold "huge positive value at the famous point", which this arrangement does not produce');
  const bandClaim = /band of lattice points where double precision returns the wrong sign|around it sits a band/i;
  P(!(wrongSign && wrongSign.dbl === 0 && bandClaim.test(html)),
    `the page does not claim a wrong-sign band for double while the census measures ${wrongSign ? wrongSign.dbl : '?'} such points`);
  // The three headline counts, as the page states them in words, against the
  // three the census just produced. Tags stripped so the check is on the
  // sentence a reader sees, not on the markup.
  const text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
  const claims = [
    [`wrong SIGN is ${wrongSign.dbl}`, 'double'],
    [`sign wrong at ${wrongSign.sgl} of them`, 'single'],
    [`double-double at exactly ${wrongSign.dd}`, 'double-double'],
  ];
  for (const [phrase, which] of claims) {
    P(text.includes(phrase),
      `the page states the measured ${which} wrong-sign count as the census found it ("${phrase}")`);
  }
}

// ---------------------------------------------------------------- 010 negative controls on this verifier
{
  const gTrue = gBig(77617, 33096, 121);
  const gMut = gBig(77617, 33096, 122);
  CONTROL(gMut !== gTrue,
    'mutating coefficient 121 -> 122 moves the exact centre value, so the battery comparison has a real difference to catch');
}
{
  const row = { label: 'control-window', p0: 2, p1: 0, chunks: 5 };
  const ctx = ctxFor(row);
  const inst2 = makeInst();
  inst2.init(ctx.p0, ctx.p1);
  const fullAcc = ctx.initial.call(ctx);
  const partAcc = ctx.initial.call(ctx);
  for (let i = 0; i < ctx.chunks; i++) {
    const c = inst2.chunk(0, i, ctx.chunks);
    const dv = new DataView(c.out.buffer);
    ctx.reduce.call(ctx, fullAcc, dv, i, 0);
    if (i < ctx.chunks - 1) ctx.reduce.call(ctx, partAcc, dv, i, 0);
  }
  CONTROL(plan.fingerprint(fullAcc) !== plan.fingerprint(partAcc),
    'dropping one chunk of a census window changes the fingerprint, so a partitioning error cannot hide');
}

// ---------------------------------------------------------------- total
console.log('');
if (fails) {
  console.log(`FAILED: ${fails} of ${n} assertions failed`);
  process.exit(1);
}
console.log(`ALL PASS: ${n} assertions`);
