#!/usr/bin/env node
// verify-the-cosine-of-a-number-you-can-type.mjs — the offline gate.
//
//   node research/the-cosine-of-a-number-you-can-type/verify-the-cosine-of-a-number-you-can-type.mjs
//
// Node 22, no dependencies, no network. Prints one line per assertion in the
// house format, then a total, and exits non-zero on any FAIL. The full-size
// census runs twice, at the real size, under two different chunkings.

import { createHash } from 'node:crypto';
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

import * as plan from '../../public/strata/the-cosine-of-a-number-you-can-type/plan.js';
import * as ref from '../../public/strata/the-cosine-of-a-number-you-can-type/reference.js';
import * as manifest from '../../public/strata/the-cosine-of-a-number-you-can-type/manifest.js';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const DIR = path.join(ROOT, 'public', 'strata', 'the-cosine-of-a-number-you-can-type');

let nPass = 0, nFail = 0, nSkip = 0;
const t0 = Date.now();

function ok(num, msg) { nPass++; console.log(`PASS ${num}  ${msg}`); }
function bad(num, msg) { nFail++; console.log(`FAIL ${num}  ${msg}`); }
function skip(msg) { nSkip++; console.log(`SKIP  ${msg}`); }
function check(num, cond, msg) { (cond ? ok : bad)(num, msg); }
function controlLine(name, caught, detail) {
  console.log(`CONTROL ${name}  ${detail}: ${caught ? 'caught' : 'NOT CAUGHT'}`);
  if (!caught) nFail++;
}

// ------------------------------------------------------------ 1. the binary

let ex = null;
let wasmBytes = null;
try {
  wasmBytes = fs.readFileSync(path.join(DIR, 'engine.wasm'));
  const inst = new WebAssembly.Instance(new WebAssembly.Module(wasmBytes), {});
  ex = inst.exports;
} catch (e) {
  bad('001', 'engine.wasm did not load: ' + e.message);
}
if (ex) {
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_state', 'aw_state_len', 'memory'];
  const missing = need.filter((k) => !(k in ex));
  check('001', missing.length === 0, missing.length ? 'engine missing exports: ' + missing.join(', ') : 'engine instantiates with the full ABI');
}

// --------------------------------------------------------------- 2. the hash

let digest = '';
if (wasmBytes) {
  digest = createHash('sha256').update(wasmBytes).digest('hex');
  check('002', digest === String(manifest.WASM_SHA256).toLowerCase(),
    `sha256(engine.wasm) equals manifest.WASM_SHA256 (${digest.slice(0, 16)}...)`);
  const flipped = (digest[0] === '0' ? '1' : '0') + digest.slice(1);
  controlLine('C1', flipped !== digest && flipped !== String(manifest.WASM_SHA256).toLowerCase(),
    'a mutated digest is rejected by the hash comparison');
} else {
  bad('002', 'no bytes to hash');
}

// ---------------------------------------------------- 3. reproducible build

{
  const want = String(manifest.CLANG || '');
  let found = '';
  try { found = execFileSync('clang', ['--version'], { encoding: 'utf8' }).split('\n')[0]; } catch { found = ''; }
  const ver = (s) => (s.match(/\d+\.\d+\.\d+/) || [null])[0];
  if (!want || !found || ver(want) !== ver(found)) {
    skip(`reproducible build (clang ${ver(found) || 'absent'} != pinned ${ver(want) || 'none'})`);
  } else {
    const out = path.join(HERE, '.rebuild.wasm');
    try {
      execFileSync('bash', [path.join(HERE, '..', '_ox3', 'lib', 'build-wasm.sh'), path.join(DIR, 'engine.c'), out], { stdio: 'pipe' });
      const rb = fs.readFileSync(out);
      check('003', rb.equals(wasmBytes), 'rebuilding engine.c under the pinned toolchain reproduces engine.wasm byte for byte');
    } catch (e) {
      bad('003', 'rebuild failed: ' + e.message);
    } finally {
      try { fs.unlinkSync(out); } catch {}
    }
  }
}

// ------------------------------------------------------------- the runners

// per and emax come from the ROW, not from plan defaults: rebuilding p0 with
// plan.EMAX here made the wasm side of battery row 0 draw exponents from
// [-1, 79] while the reference drew from [-1, 12], so the two sides ran
// different instances and the battery could not agree for reasons that had
// nothing to do with either implementation.
function runEngine(per, emax, chunks, seed, acc, state) {
  let ops = 0n;
  ex.aw_init(plan.p0For(per, emax), seed >>> 0);
  new Uint8Array(ex.memory.buffer, ex.aw_state() >>> 0, ex.aw_state_len() >>> 0).set(state);
  for (let i = 0; i < chunks; i++) {
    const o = ex.aw_chunk(0, i >>> 0, chunks >>> 0);
    const len = ex.aw_out_len() >>> 0;
    const rec = new Uint8Array(ex.memory.buffer, ex.aw_out() >>> 0, len).slice();
    ops += BigInt.asUintN(64, typeof o === 'bigint' ? o : BigInt(o)); // the i64 boundary is signed
    plan.reduce(acc, new DataView(rec.buffer), i, 0);
  }
  return ops;
}

function runReference(row, acc, putState) {
  ref.init(row.p0, row.p1);
  putState(plan.stateBytes());
  let ops = 0n;
  for (let i = 0; i < row.chunks; i++) {
    const c = ref.chunk(0, i, row.chunks);
    ops += BigInt(c.ops);
    plan.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, 0);
  }
  return ops;
}

// ------------------------------------------------- 3b. record-path diagnostic
//
// The mechanical establishment the defect brief asked for, run on EVERY gate
// pass so the question is settled by printout, not by argument. Take the
// smallest census argument (gi = 0), run it through BOTH implementations on
// the primary instance, and print: the argument bits from both sides
// (asserted equal: a mismatch would put the fault upstream of the record),
// the quadrant n and the reduced argument r (from the reference's BigInt
// reduction; the ABI record carries no n or r, and the engine's reduction is
// pinned by the bitwise battery and the pythagorean and range invariants),
// and the raw 64-bit pattern each side actually compares. If the reduced
// argument and quadrant agree while the compared patterns differ, the value
// written into the record is wrong at its source, and no reader is at fault.
if (ex) {
  const perD = 4;
  const p0D = plan.p0For(perD, plan.EMAX);
  const stateD = plan.stateBytes();
  ex.aw_init(p0D, plan.SEED >>> 0);
  new Uint8Array(ex.memory.buffer, ex.aw_state() >>> 0, ex.aw_state_len() >>> 0).set(stateD);
  ex.aw_chunk(0, 0, 1);
  const dlen = ex.aw_out_len() >>> 0;
  const ddv = new DataView(new Uint8Array(ex.memory.buffer, ex.aw_out() >>> 0, dlen).slice().buffer);
  const engXB = ddv.getBigUint64(16, true);
  const engCB = ddv.getBigUint64(16 + 8 * perD, true);
  ref.init(p0D, plan.SEED);
  ref.putState(stateD);
  const rc = ref.chunk(0, 0, 1);
  const rdv = new DataView(rc.out.buffer, rc.out.byteOffset, rc.out.byteLength);
  const refXB = rdv.getBigUint64(16, true);
  const refCB = rdv.getBigUint64(16 + 8 * perD, true);
  const di = ref.reduceDebug(0);
  const hx = (v) => '0x' + BigInt.asUintN(64, v).toString(16).padStart(16, '0');
  console.log(`      diag gi=0: xb engine ${hx(engXB)}  reference ${hx(refXB)}  ${engXB === refXB ? 'match' : 'MISMATCH'}`);
  console.log(`      diag gi=0: n ${di.n}  n mod 4 ${di.n & 3n}  r ${di.neg ? '-' : '+'}${hx(di.rHi)} ${hx(di.rLo)}  (reference BigInt reduction; exact integer path on both sides)`);
  console.log(`      diag gi=0: compared patterns  engine ${hx(engCB)}  reference ${hx(refCB)}  ${engCB === refCB ? 'match' : 'DIFFER'}`);
}

// ------------------------------------------------------------- 4. battery

const wasmFps = [];
let allAgree = true;
for (const row of plan.battery) {
  const accW = plan.initial();
  runEngine(row.p0 & 0xFFFF, row.p0 >>> 16, row.chunks, row.p1, accW, plan.stateBytes());
  const accR = plan.initial();
  runReference(row, accR, (s) => ref.putState(s));
  const fw = plan.fingerprint(accW), fr = plan.fingerprint(accR);
  wasmFps.push(fw);
  if (fw !== fr) allAgree = false;
  console.log(`      row "${row.label}": wasm ${fw}  ref ${fr}  ${fw === fr ? 'agree' : 'DISAGREE'}`);
}
check('004', allAgree, 'battery: wasm and reference fingerprints agree on every row');
// 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.
check('005', new Set(wasmFps).size >= 2, 'battery exercises ' + new Set(wasmFps).size +
  ' distinct instance(s) across ' + wasmFps.length + ' rows' +
  (new Set(wasmFps).size < wasmFps.length ? ', ' + (wasmFps.length - new Set(wasmFps).size) + ' agreeing across a different decomposition' : ''));
{
  const mut = (wasmFps[0][0] === '0' ? '1' : '0') + wasmFps[0].slice(1);
  controlLine('C2', mut !== wasmFps[0], 'a mutated battery fingerprint fails the agreement comparison');
}

// ------------------------------------------------------------- 5. control

{
  const broken = plan.breakReference(ref);
  const fpsB = [];
  for (const row of plan.battery) {
    const accB = plan.initial();
    runReference(row, accB, (s) => broken.putState(s));
    fpsB.push(plan.fingerprint(accB));
  }
  const caught = fpsB.filter((f, i) => f !== wasmFps[i]).length;
  check('006', broken !== ref && caught >= 1,
    `control: breakReference returns a different object and the broken reference disagrees on ${caught}/${plan.battery.length} rows`);
  check('007', fpsB[0] === wasmFps[0], 'control: the small-argument battery row is untouched by the break');
}

// ----------------------------------------------------- 6. planted witness

// Feed one double to the UNMODIFIED engine through the state channel a typed
// number uses, and read the answer back out of the contract's answer slot:
// the SECOND f64 slot, 16 + 8(per + k), per the contract the engine's own
// header documents and the reference follows. Reading the first slot took the
// argument and failed 0/53 against a correct engine.
function plantOne(xb) {
  ex.aw_init(plan.p0For(64, plan.EMAX), 0x5EED1);
  new Uint8Array(ex.memory.buffer, ex.aw_state() >>> 0, ex.aw_state_len() >>> 0)
    .set(plan.stateBytes({ plantX: xb, plantIdx: 37 }));
  let got = null;
  for (let i = 0; i < 2; i++) {
    ex.aw_chunk(0, i, 2);
    const len = ex.aw_out_len() >>> 0;
    const dv = new DataView(new Uint8Array(ex.memory.buffer, ex.aw_out() >>> 0, len).slice().buffer);
    const per = dv.getUint32(0, true);
    const base = i * per;
    if (37 >= base && 37 < base + per) got = dv.getFloat64(16 + 8 * (per + (37 - base)), true);
  }
  return got;
}

// floor(sqrt(n)) on BigInt, by Newton. Used to produce sqrt(3)/2 from the
// integer 3 alone, so the quadrant witnesses below are held to a value no
// cosine, no table on this page, and no platform library had any part in.
function isqrt(n) {
  if (n < 2n) return n;
  let x = n, y = (x + 1n) >> 1n;
  while (y < x) { x = y; y = (x + n / x) >> 1n; }
  return x;
}

let gotPlanted = null;
{
  const pl = plan.makePlanted();
  gotPlanted = plantOne(pl.xb);
  const px = plan.bitsToDouble(pl.xb);
  const pe = plan.bitsExp(pl.xb);
  console.log(`      planted x* = ${px} (exponent ${pe}, inside the census range [-1, ${plan.EMAX}]), n mod 4 = ${pl.ev.q}`);
  const b = plan.bitsAgree(gotPlanted, pl.expectedDouble);
  check('008', b === 53, `planted witness: the unmodified engine returns the constructed answer bitwise (${b}/53 bits)`);
  const bumped = plan.bitsToDouble(plan.doubleToBits(pl.expectedDouble) + 1n);
  controlLine('C3', plan.bitsAgree(gotPlanted, bumped) < 53, 'a one-ulp-wrong expectation fails the planted check');
  check('015', pe >= -1 && pe <= plan.EMAX,
    `planted witness: x* is the double nearest ${plan.PLANT_N} * pi/2 and its exponent ${pe} is inside the range the engine is defined on`);
}

// ------------------------------------- 6b. the quadrant witnesses
//
// The big witness lands in whichever quadrant it lands in, so on its own it
// drives one branch of cos(r + n*pi/2) out of four. These eight are placed at
// (j +- 1/3)*pi/2, small enough that an ulp is far below pi/4, so the quadrant
// and the sign of r are fixed by construction and every branch is driven with
// r on both sides of zero. Each answer is then held to TWO standards: the
// engine's 128-bit path against plan.js's 192-bit path, bitwise; and both
// against sqrt(3)/2 or 1/2, which is what cos((j +- 1/3)*pi/2) is
// algebraically. The second one is the instrument that does not read the
// spec: it would have caught an engine that emitted the cosine of the reduced
// argument instead of cos x, which is exactly what this engine did, and it
// never consults Math.
{
  const SCALE = 10n ** 40n;
  const ROOT3_HALF = Number(isqrt(3n * SCALE * SCALE) / 2n) / Number(SCALE);  // sqrt(3)/2
  const ulpOf = (v) => 2 ** (plan.bitsExp(plan.doubleToBits(Math.abs(v))) - 52);
  // The witness is cos(x*) where x* is the double NEAREST (j +- 1/3)*pi/2, not
  // that number itself, so it cannot equal the algebraic constant exactly. The
  // gap is bounded by the mean value theorem and nothing else:
  //     |cos x* - cos t| <= |sin t| * |x* - t| <= |sin t| * ulp(x*)/2
  // and one more ulp of the answer for its own rounding to a double. Both
  // |sin t| values are the same two constants, swapped: at (j +- 1/3)*pi/2 the
  // cosine is +-sqrt(3)/2 and the sine +-1/2 when j is even, and the other way
  // round when j is odd. So the tolerance is derived per witness, printed, and
  // is not a number anyone chose.
  let bitwise = 0, algebraic = 0, worstRatio = 0, worstLine = '';
  const lines = [];
  for (const [j, sg] of plan.PLANT_CASES) {
    const pl = plan.makePlantedOffset(j, sg);
    const got = plantOne(pl.xb);
    if (plan.bitsAgree(got, pl.expectedDouble) === 53) bitwise++;
    const x = plan.bitsToDouble(pl.xb);
    const want = (j % 2 === 0 ? ROOT3_HALF : 0.5) * Math.sign(pl.expectedDouble);
    const sinMag = (j % 2 === 0 ? 0.5 : ROOT3_HALF);
    const bound = sinMag * (ulpOf(x) / 2) / ulpOf(want) + 1;
    const seen = Math.abs(got - want) / ulpOf(want);
    if (seen <= bound) algebraic++;
    if (seen / bound > worstRatio) {
      worstRatio = seen / bound;
      worstLine = `${seen.toFixed(2)} ulp against a bound of ${bound.toFixed(2)}`;
    }
    lines.push(`n mod 4=${pl.ev.q} r${sg > 0 ? '>' : '<'}0 ${got} (${seen.toFixed(1)}/${bound.toFixed(1)} ulp)`);
  }
  console.log('      quadrant witnesses: ' + lines.join(' | '));
  check('016', bitwise === plan.PLANT_CASES.length,
    `quadrant witnesses: the engine matches the 192-bit path bitwise in all four quadrants, both signs of r (${bitwise}/${plan.PLANT_CASES.length})`);
  check('017', algebraic === plan.PLANT_CASES.length,
    `quadrant witnesses: every answer is the sqrt(3)/2 or 1/2 integer arithmetic says it must be, inside the bound the argument's own rounding forces (worst ${worstLine})`);
  // Two controls, because the assertion has two ways of being vacuous: the
  // wrong constant must fail it, and the bound must be tight enough that a
  // wrong quadrant's answer does not slip through it.
  const pl0 = plan.makePlantedOffset(0, 1);
  const g0 = plantOne(pl0.xb);
  controlLine('C5', Math.abs(g0 - 0.5) / ulpOf(0.5) > 1 + 0.5 * (ulpOf(plan.bitsToDouble(pl0.xb)) / 2) / ulpOf(0.5),
    'holding a sqrt(3)/2 witness to 1/2 instead fails the algebraic check');
  controlLine('C7', Math.abs(g0 - ROOT3_HALF) / ulpOf(ROOT3_HALF) <= 2 &&
    Math.abs(-g0 - ROOT3_HALF) / ulpOf(ROOT3_HALF) > 2,
    'the algebraic check is sign-sensitive: the negated answer fails it');
}

// ------------------------------- 6c. the invariant nobody wrote the code for
//
// cos 2x = 2 cos^2 x - 1, and 2x is exact in binary. This is the one check on
// this page that the engine was not built to satisfy: x and 2x reduce against
// completely different multiples of pi/2, land in different quadrants, and
// take different branches, so the identity relates two independent runs of
// the whole path. It reads no second implementation, no platform cosine and
// no part of the contract. If the reduction were wrong in a way both
// implementations shared, this is what would still say so.
//
// The tolerance is the rounding of a double and nothing else. With
// c = fl(cos x) = cos x + d and |d| <= 2^-53,
//     2c^2 - 1 = cos 2x + 4 c d + 2 d^2,
// so the identity can miss by 4|c||d| <= 2^-51, plus at most one rounding
// each for c*c, for the subtraction, and for cos 2x itself: under 2^-50.
{
  const LIMIT = 2 ** -50;
  const SAMPLE = 1500;
  let worst = 0, worstX = 0, checked = 0;
  for (let gi = 0; gi < SAMPLE; gi++) {
    const xb = plan.argBitsFor(gi, plan.SEED, plan.EMAX - 1); // e <= 78 keeps 2x in range
    const x = plan.bitsToDouble(xb);
    const c = plantOne(xb);
    const c2 = plantOne(plan.doubleToBits(2 * x));
    const dev = Math.abs(c2 - (2 * c * c - 1));
    checked++;
    if (dev > worst) { worst = dev; worstX = x; }
  }
  check('018', checked === SAMPLE && worst <= LIMIT,
    `double-angle: cos 2x equals 2cos^2 x - 1 across ${checked} census arguments, worst ${worst.toExponential(3)} against the 2^-50 the double format allows (worst at x = ${worstX})`);
  // The control: the same identity must reject an answer that is wrong by an
  // amount the format does not excuse. 64 ulps is far below anything a broken
  // reduction would produce and still has to be caught.
  const xb0 = plan.argBitsFor(0, plan.SEED, plan.EMAX - 1);
  const c0 = plantOne(xb0);
  const nudged = plan.bitsToDouble(plan.doubleToBits(c0) + 64n);
  const c20 = plantOne(plan.doubleToBits(2 * plan.bitsToDouble(xb0)));
  controlLine('C8', Math.abs(c20 - (2 * nudged * nudged - 1)) > LIMIT,
    'a cosine wrong by 64 ulps fails the double-angle identity');
}

// --------------------------------------------------------- 7. pi identity

{
  const C = plan.computeConstants();
  check('009', C.agree >= 500 && C.keep >= plan.NBITS + 64,
    `pi: the two Machin formulas agree on ${C.agree} of ${plan.SBITS} bits; ${C.keep} kept, tables pinned by bracketing`);
}

// --------------------------------------------- 8. the full-size decomposition

let acc1 = null, acc2 = null, ops1 = 0n, ops2 = 0n;
{
  console.log(`      full-size pass 1: ${plan.CHUNKS} chunks x ${plan.PER} arguments ...`);
  acc1 = plan.initial();
  let t = Date.now();
  ops1 = runEngine(plan.PER, plan.EMAX, plan.CHUNKS, plan.SEED, acc1, plan.stateBytes());
  console.log(`      pass 1 done in ${((Date.now() - t) / 1000).toFixed(1)} s`);

  console.log(`      full-size pass 2: ${plan.ALT_CHUNKS} chunks x ${plan.ALT_PER} arguments ...`);
  acc2 = plan.initial();
  t = Date.now();
  ops2 = runEngine(plan.ALT_PER, plan.EMAX, plan.ALT_CHUNKS, plan.SEED, acc2, plan.stateBytes());
  console.log(`      pass 2 done in ${((Date.now() - t) / 1000).toFixed(1)} s`);

  check('010', plan.canonicalDump(acc1) === plan.canonicalDump(acc2),
    'full-size: the second decomposition reproduces every per-decade histogram, worst case and counter exactly');
  check('011', ops1 === ops2 && ops1 > 0n, `full-size: the engine's own op counter is identical across decompositions (${ops1})`);
  check('012',
    acc1.pythViolations === 0 && acc1.nearTies === 0 && acc1.rangeViolations === 0 &&
    acc2.pythViolations === 0 && acc2.nearTies === 0 && acc2.rangeViolations === 0,
    'full-size: pythagorean, near-tie and range invariants hold at every census point');
  check('013', acc1.rfBad === 0,
    `full-size: reduction-free cross-method within 1 ulp everywhere (${acc1.rfExact}/${acc1.rfTotal} bitwise exact)`);
  const obj = JSON.parse(plan.canonicalDump(acc1));
  obj.hist[0][0] += 1;
  controlLine('C4', JSON.stringify(obj) !== plan.canonicalDump(acc1), 'a mutated histogram cell fails the decomposition comparison');
}

// ------------------------------------------------- 9. the page's own facts

{
  let html = '';
  try { html = fs.readFileSync(path.join(DIR, 'index.html'), 'utf8'); } catch (e) { bad('014', 'cannot read index.html: ' + e.message); }
  if (html) {
    // Every row is a [token, name] pair. The primary-chunking row used to be
    // two bare strings instead of one pair, and the normaliser under it turned
    // each into [firstChar, secondChar]: the gate was asking whether the page
    // contained the character "1" and the character "p". Two of the eight
    // facts were therefore checked by something that could not fail. Left as
    // a plain array with no normaliser, so the shape cannot drift again.
    const facts = [
      [plan.fmtInt(plan.TOTAL), 'census size'],
      [`${plan.fmtInt(plan.CHUNKS)} × ${plan.fmtInt(plan.PER)}`, 'primary chunking'],
      [`${plan.fmtInt(plan.ALT_CHUNKS)} × ${plan.fmtInt(plan.ALT_PER)}`, 'second chunking'],
      [String(plan.NBITS), 'stored bits of 2/pi'],
      ['0x' + plan.PIO2_HEX, 'the double nearest pi/2'],
      ['0x' + plan.SEED_HEX, 'census seed'],
      ['2^-120', 'certification bound'],
      ['arctan(1/239)', 'Machin formula'],
    ];
    if (facts.some((f) => !Array.isArray(f) || f.length !== 2)) {
      bad('014', 'the fact list is malformed: a row is not a [token, name] pair');
    } else {
      const missing = facts.filter(([tok]) => !html.includes(tok)).map(([, name]) => name);
      check('014', missing.length === 0,
        missing.length ? 'page omits stated facts: ' + missing.join(', ') : 'every fixed figure the page states appears in the shipped HTML');
      // Run the same filter over the same list plus one token the page cannot
      // contain, and require it to come back named. Without this, "no facts
      // missing" would be indistinguishable from a filter that finds nothing.
      const probe = facts.concat([[`${plan.fmtInt(plan.TOTAL)} \u00d7 ${plan.fmtInt(plan.TOTAL)}`, 'deliberately absent']]);
      const probeMissing = probe.filter(([tok]) => !html.includes(tok)).map(([, name]) => name);
      controlLine('C6', probeMissing.length === 1 && probeMissing[0] === 'deliberately absent',
        'the fact check names a figure the page does not state');
    }
  }
}

// ------------------------------------------------------------------ total

console.log(`
${nPass} passed, ${nFail} failed, ${nSkip} skipped  (${((Date.now() - t0) / 1000).toFixed(1)} s)`);
process.exit(nFail ? 1 : 0);
