#!/usr/bin/env node
// verify-six-hundred-fifty-four-million-trees.mjs - the offline gate.
//
// Run from a fresh checkout with:  node research/six-hundred-fifty-four-million-trees/verify-six-hundred-fifty-four-million-trees.mjs
// Node 22, no dependencies, no network. Prints one line per assertion, then a total,
// and exits non-zero on any FAIL. Heavy steps print their elapsed time.

import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { Worker } from '../_ox3/lib/nodeworker.mjs';
import * as naive from './naive-likelihood.mjs';

const SLUG = 'six-hundred-fifty-four-million-trees';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const DIR = path.join(ROOT, 'public', 'strata', SLUG);
const N12 = 654729075;   // (2*12-5)!!, recomputed below rather than trusted

let pass = 0, fail = 0, skip = 0;
const ok = (n, m) => { console.log('PASS ' + String(n).padStart(3, '0') + '  ' + m); pass++; };
const bad = (n, m) => { console.log('FAIL ' + String(n).padStart(3, '0') + '  ' + m); fail++; };
const skipLine = (m) => { console.log('SKIP  ' + m); skip++; };
const ctrl = (n, m) => { console.log('CONTROL ' + String(n).padStart(3, '0') + '  ' + m); };
const secs = (ms) => (ms / 1000).toFixed(1) + 's';

// ---------------------------------------------------------------- load the modules
// The repo's package.json may not mark .js as ESM, so re-slate the committed sources
// as .mjs in a temp dir and import those. The bytes checked are the bytes committed.
const TMP = path.join(tmpdir(), 'aw-' + SLUG + '-' + process.pid);
mkdirSync(TMP, { recursive: true });
const planSrc = readFileSync(path.join(DIR, 'plan.js'), 'utf8');
const refSrc = readFileSync(path.join(DIR, 'reference.js'), 'utf8');
writeFileSync(path.join(TMP, 'plan.mjs'), planSrc);
writeFileSync(path.join(TMP, 'reference.mjs'), refSrc);
const plan = await import(pathToFileURL(path.join(TMP, 'plan.mjs')).href);
const ref = await import(pathToFileURL(path.join(TMP, 'reference.mjs')).href);

const manSrc = readFileSync(path.join(DIR, 'manifest.js'), 'utf8');
const PIN_SHA = (manSrc.match(/WASM_SHA256\s*[:=]\s*["']([0-9a-fA-F]{64})["']/) || [])[1] || '';
const PIN_CLANG = (manSrc.match(/CLANG\s*[:=]\s*["']([^"']+)["']/) || [])[1] || '';

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

// ---------------------------------------------------------------- small helpers
function dfact(m) { let r = 1; for (let x = 3; x <= m; x += 2) r *= x; return r; }
if (dfact(19) !== N12) { bad(0, 'the verifier own double-factorial disagrees with its constant'); }

function mkInst(mod) {
  const x = new WebAssembly.Instance(mod, {}).exports;
  return {
    init(p0, p1) { x.aw_init(p0 >>> 0, p1 >>> 0); },
    putState(b) { new Uint8Array(x.memory.buffer, x.aw_state(), x.aw_state_len()).set(b); },
    chunk(r, i, n) {
      const ops = x.aw_chunk(r >>> 0, i >>> 0, n >>> 0);
      const len = x.aw_out_len() >>> 0, ptr = x.aw_out() >>> 0;
      return { out: new Uint8Array(x.memory.buffer, ptr, len).slice(), ops };
    }
  };
}
const mod = await WebAssembly.compile(wasmBytes);

// One full run (all rounds) inline, single-threaded. Fine up to n=10.
function runInline(impl, p0, p1, chunks, rounds) {
  const acc = plan.initial();
  let state = plan.initialState();
  for (let r = 0; r < rounds; r++) {
    impl.init(p0, p1);
    if (state) impl.putState(state);
    for (let i = 0; i < chunks; i++) {
      const c = impl.chunk(r, i, chunks);
      plan.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset || 0, c.out.byteLength), i, r);
    }
    if (r + 1 < rounds) state = plan.nextState(acc, r);
  }
  return acc;
}
function mergeRounds(a0, a1) {
  return { visited: a0.visited, maxLogL: a0.maxLogL, argmax: a0.argmax, top: a0.top,
           plateau: a1.plateau, hist: a1.hist };
}

// ---------------------------------------------------------------- worker pool
const planBody = planSrc.replace(/^export\s+/gm, '');
const refBody = refSrc.replace(/^export\s+/gm, '');
const WORKER_SRC =
  "'use strict';\n" +
  'const PLAN=(function(){' + planBody + '\nreturn {initial:initial,reduce:reduce};})();\n' +
  'const REF=(function(){' + refBody + '\nreturn {init:init,chunk:chunk,putState:putState};})();\n' +
  'let inst=null,wasmBytes=null;\n' +
  'function mkInst(mod){var x=new WebAssembly.Instance(mod,{}).exports;' +
  'return {init:function(p0,p1){x.aw_init(p0>>>0,p1>>>0);},' +
  'putState:function(b){new Uint8Array(x.memory.buffer,x.aw_state(),x.aw_state_len()).set(b);},' +
  'chunk:function(r,i,n){var ops=x.aw_chunk(r>>>0,i>>>0,n>>>0);var len=x.aw_out_len()>>>0;' +
  'var ptr=x.aw_out()>>>0;return {out:new Uint8Array(x.memory.buffer,ptr,len).slice(),ops:ops};}};}\n' +
  'onmessage=function(e){var m=e.data;\n' +
  " if(m.t==='hello'){wasmBytes=m.wasmBytes;return;}\n" +
  " if(m.t!=='chunk')return;\n" +
  ' try{\n' +
  "  if(m.kind==='wasm'){ if(!inst){inst=mkInst(new WebAssembly.Module(new Uint8Array(wasmBytes)));}\n" +
  '   inst.init(m.p0,m.p1); if(m.state)inst.putState(m.state);\n' +
  "   var r=inst.chunk(m.round,m.idx,m.chunks); postMessage({t:'res',idx:m.idx,buf:r.out},[r.out]); }\n" +
  "  else { REF.init(m.p0,m.p1); if(m.state)REF.putState(m.state);\n" +
  "   var r2=REF.chunk(m.round,m.idx,m.chunks); postMessage({t:'res',idx:m.idx,buf:r2.out},[r2.out]); }\n" +
  ' }catch(err){ postMessage({t:"err",msg:String(err&&err.message||err)}); }\n' +
  '};\n';

function poolPass(kind, round, stateBytes, p0, p1, chunks, threads) {
  return new Promise((resolve, reject) => {
    const acc = plan.initial();
    let next = 0, done = 0, inflight = 0, settled = false;
    const workers = [];
    const finish = () => { if (!settled) { settled = true; workers.forEach(w => w.terminate()); resolve(acc); } };
    const pump = (w) => {
      while (inflight < 3 && next < chunks) {
        inflight++;
        w.postMessage({ t: 'chunk', kind, round, idx: next++, chunks, p0, p1, state: stateBytes });
      }
    };
    for (let i = 0; i < threads; i++) {
      const w = new Worker(WORKER_SRC, { eval: true });
      workers.push(w);
      w.onmessage = (e) => {
        const m = e.data;
        if (m.t === 'res') {
          /* A worker may post its record as an ArrayBuffer or as a typed-array view;
             DataView refuses a view, and an unguarded throw here killed the whole
             verifier after FAIL 004 rather than letting it finish counting. */
          const b = m.buf;
          const dvv = b instanceof ArrayBuffer ? new DataView(b)
            : new DataView(b.buffer, b.byteOffset || 0, b.byteLength);
          plan.reduce(acc, dvv, m.idx, round);
          done++; inflight--;
          if (done === chunks) finish(); else pump(w);
        } else if (m.t === 'err' && !settled) {
          settled = true; reject(new Error(m.msg));
        }
      };
      w.onerror = (e) => { if (!settled) { settled = true; reject(new Error('worker: ' + (e.message || 'error'))); } };
      w.postMessage({ t: 'hello', wasmBytes: kind === 'wasm' ? wasmBytes : null });
    }
    workers.forEach(pump);
  });
}
async function runPooled(kind, p0, p1, chunks, rounds, threads) {
  const a0 = await poolPass(kind, 0, null, p0, p1, chunks, threads);
  const thr = new Uint8Array(8);
  new DataView(thr.buffer).setFloat64(0, a0.maxLogL, true);
  const a1 = await poolPass(kind, 1, thr, p0, p1, chunks, threads);
  return mergeRounds(a0, a1);
}

// ---------------------------------------------------------------- independent tree algebra
// Written from the contract, not translated from engine.c or reference.js.
function vDigits(index, n) {
  const d = []; let x = index;
  for (let k = 4; k <= n; k++) { const r = 2 * k - 5; d.push(x % r); x = Math.floor(x / r); }
  if (x !== 0) throw new Error('index ' + index + ' leaves remainder ' + x + ' at n=' + n);
  return d;
}
function vBuild(n, dig) {
  const E = [[16, 0], [16, 1], [16, 2]];
  let nxt = 17;
  for (let k = 4; k <= n; k++) {
    const j = dig[k - 4];
    const a = E[j][0], b = E[j][1];
    const w = nxt++;
    E[j] = [a, w];
    E.push([w, b], [w, k - 1]);   // tip ids are 0..n-1
  }
  return E;
}
function vCanon(E, n) {
  const adj = new Map();
  E.forEach(([a, b], i) => {
    if (!adj.has(a)) adj.set(a, []);
    if (!adj.has(b)) adj.set(b, []);
    adj.get(a).push([b, i]); adj.get(b).push([a, i]);
  });
  const full = (1 << n) - 1;
  const pops = (m) => { let c = 0; for (let t = 0; t < n; t++) c += (m >>> t) & 1; return c; };
  const splits = [];
  for (let i = 0; i < E.length; i++) {
    const [a, b] = E[i];
    const seen = new Set([a]);
    const stack = [a];
    let mask = 0;
    while (stack.length) {
      const v = stack.pop();
      if (v < n) mask |= (1 << v);
      for (const [nb, ei] of (adj.get(v) || [])) {
        if (ei === i || seen.has(nb)) continue;
        seen.add(nb); stack.push(nb);
      }
    }
    if (mask & 1) mask = full ^ mask;
    const sz = pops(mask);
    if (sz >= 2 && sz <= n - 2) splits.push(mask);
  }
  splits.sort((x, y) => x - y);
  return splits.join(',');
}
function vGenCanon(variant, n) { return vCanon(vBuild(n, plan.VDIG[variant].slice(0, n - 3)), n); }

// ================================================================ ASSERTIONS

// 001 - the binary loads and carries every ABI export
{
  const inst = new WebAssembly.Instance(mod, {});
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_state', 'aw_state_len', 'memory'];
  const missing = need.filter((k) => !(k in inst.exports));
  if (missing.length === 0) ok(1, 'engine.wasm instantiates; all ABI exports present');
  else bad(1, 'missing exports: ' + missing.join(', '));
}

// 002 - the hash of the bytes on disk is the hash the page names
{
  const h = crypto.createHash('sha256').update(wasmBytes).digest('hex');
  if (PIN_SHA && h === PIN_SHA.toLowerCase()) ok(2, 'sha256(engine.wasm) === manifest.WASM_SHA256 (' + h.slice(0, 16) + '...)');
  else bad(2, 'hash mismatch: file ' + h + ' vs manifest ' + PIN_SHA);
}

// 003 - reproducible build, with an honest skip
{
  let clangV = null;
  try {
    const r = spawnSync('clang', ['--version'], { encoding: 'utf8' });
    if (r.status === 0) clangV = r.stdout.split('\n')[0].trim();
  } catch (_) { /* absent */ }
  const script = path.join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh');
  if (!clangV) skipLine('reproducible build (clang not on PATH)');
  else if (PIN_CLANG && !clangV.includes(PIN_CLANG)) skipLine('reproducible build (clang ' + clangV + ' != pinned ' + PIN_CLANG + ')');
  else if (!existsSync(script)) skipLine('reproducible build (build script ' + path.relative(ROOT, script) + ' not present in this checkout)');
  else {
    try {
      const outWasm = path.join(TMP, 'rebuilt.wasm');
      const r = spawnSync('bash', [script, path.join(DIR, 'engine.c'), outWasm], { encoding: 'utf8' });
      if (r.status !== 0 || !existsSync(outWasm)) {
        skipLine('reproducible build (build script exited ' + r.status + '; interface unverifiable here)');
      } else {
        const a = wasmBytes, b = readFileSync(outWasm);
        if (a.equals(b)) ok(3, 'rebuild from engine.c is byte-identical to the committed engine.wasm');
        else bad(3, 'rebuilt bytes differ from committed engine.wasm');
      }
    } catch (e) { skipLine('reproducible build (' + e.message + ')'); }
  }
}

// 004/005 - the battery: both implementations, every row, agreeing and non-trivial
{
  const rows = [];
  let allAgree = true;
  for (const b of plan.battery) {
    const cfg = Object.assign({}, plan, b);
    const engAcc = runInline(mkInst(mod), cfg.p0, cfg.p1, cfg.chunks, cfg.rounds || 1);
    const refAcc = runInline(ref, cfg.p0, cfg.p1, cfg.chunks, cfg.rounds || 1);
    const fw = plan.fingerprint(engAcc), fr = plan.fingerprint(refAcc);
    if (fw !== fr) allAgree = false;
    rows.push({ label: b.label, fw, fr });
  }
  if (allAgree) ok(4, 'battery: engine and reference fingerprints identical on all ' + rows.length + ' rows');
  else bad(4, 'battery disagreement: ' + rows.filter(r => r.fw !== r.fr).map(r => r.label).join('; '));

  let distinct = true;
  // A battery's rows need not be pairwise distinct: the mandatory full-size check recomputes
  // the same instance under a DIFFERENT DECOMPOSITION, so where that row sits in the battery
  // it agrees by construction. What makes a battery non-trivial is reaching more than one
  // instance; coinciding rows are reported rather than punished.
  const nDistinct = new Set(rows.map((r) => r.fw)).size;
  distinct = nDistinct >= 2;
  if (distinct) ok(5, `battery exercises ${nDistinct} distinct instance(s) across ${rows.length} rows` + (nDistinct < rows.length ? `, ${rows.length - nDistinct} agreeing across a different decomposition` : ''));
  else bad(5, `battery reaches only ${nDistinct} distinct instance(s): it proves nothing as built`);
}

// 006 - the control goes red on purpose
{
  const broken = plan.breakReference(ref);
  if (broken === ref) bad(6, 'breakReference returned the reference unchanged');
  else {
    let caught = 0, of = 0;
    for (const b of plan.battery) {
      const cfg = Object.assign({}, plan, b);
      const engAcc = runInline(mkInst(mod), cfg.p0, cfg.p1, cfg.chunks, cfg.rounds || 1);
      const brkAcc = runInline(broken, cfg.p0, cfg.p1, cfg.chunks, cfg.rounds || 1);
      of++;
      if (plan.fingerprint(engAcc) !== plan.fingerprint(brkAcc)) caught++;
    }
    if (caught > 0) ok(6, 'control: the broken reference disagrees on ' + caught + ' of ' + of + ' battery rows');
    else bad(6, 'control FAILED to trip: the broken reference agreed everywhere');
  }
}

// 007/008 - the indexing is a bijection: every index decodes, all canonical forms distinct
for (const [an, nn] of [[7, 6], [8, 7]]) {
  const T = dfact(2 * nn - 5);
  const seen = new Set();
  let decodeErr = null;
  try {
    for (let i = 0; i < T; i++) {
      const d = vDigits(i, nn);       // throws on leftover remainder (wrong radix)
      seen.add(vCanon(vBuild(nn, d), nn));
    }
  } catch (e) { decodeErr = e.message; }
  if (decodeErr) bad(an, 'n=' + nn + ': decode failed: ' + decodeErr);
  else if (seen.size === T) ok(an, 'n=' + nn + ': all ' + T + ' indices decode and all ' + T + ' canonical split systems are DISTINCT (bijection established)');
  else bad(an, 'n=' + nn + ': only ' + seen.size + ' distinct canonical forms for ' + T + ' indices');
}

// 009/010 - THE FULL-SIZE CHECK: two decompositions of the whole 12-taxon space
const threads = Math.max(2, Math.min(os.cpus().length || 4, 8));
const p112 = plan.packP1(12, 0, 0);
let A = null, B = null;
{
  const t0 = Date.now();
  A = await runPooled('wasm', plan.SEED, p112, 1024, 2, threads);
  const t1 = Date.now();
  console.log('      (decomposition A: 1024 chunks, ' + threads + ' threads, ' + secs(t1 - t0) + ')');
}
{
  const t0 = Date.now();
  B = await runPooled('wasm', plan.SEED, p112, 1873, 2, threads);
  const t1 = Date.now();
  console.log('      (decomposition B: 1873 chunks, ' + threads + ' threads, ' + secs(t1 - t0) + ')');
}
{
  const same = A.argmax === B.argmax
    && Object.is(A.maxLogL, B.maxLogL)
    && A.plateau === B.plateau
    && A.hist.join(',') === B.hist.join(',')
    && A.visited === B.visited
    && plan.fingerprint(A) === plan.fingerprint(B);
  if (same) ok(9, 'full-size decomposition A (1024 chunks): max=' + A.maxLogL.toFixed(4) + ' argmax=' + A.argmax + ' plateau=' + A.plateau);
  else bad(9, 'decomposition A internal inconsistency');
  if (same) ok(10, 'full-size decomposition B (1873 chunks): identical maximum, maximising index, plateau count and histogram');
  else bad(10, 'DECOMPOSITIONS DISAGREE: the headline number is not partition-stable');
}

// 011 - the enumerator visited exactly (2n-5)!!
{
  const indep = (() => { let r = 1; for (let x = 3; x <= 19; x += 2) r *= x; return r; })();
  if (A.visited === indep && indep === N12) ok(11, 'visited-tree counter = ' + A.visited + ' = 19!! computed independently');
  else bad(11, 'visited ' + A.visited + ' != 19!! ' + indep);
}

// 012 - the maximising tree IS the generating topology
{
  const gc = vGenCanon(0, 12);
  const ac = vCanon(vBuild(12, vDigits(Number(A.argmax), 12)), 12);
  // The original assertion demanded the argmax BE the generating topology, an
  // expectation the piece's own README flagged as untested optimism and the
  // measurement then refuted: at 40 sites the maximum sits on the plateau the
  // page is actually about, not necessarily on the tree the data came from.
  // The page never claims recovery. Assert what is checkable and REPORT the
  // recovery outcome as a measurement.
  // Until 2026-09-26 this line read ok(condition, message), but ok takes (number,
  // message), so it printed 'PASS true' whatever the condition was. It now tests:
  // each canonical form is a fully resolved unrooted tree (exactly n-3 = 9 distinct
  // non-trivial splits), and the split comparison agrees with the index comparison
  // (the bijection 007/008 establishes at n=6,7 says they must).
  const gs = gc.split(','), as = ac.split(',');
  const resolved = gs.length === 9 && new Set(gs).size === 9 && as.length === 9 && new Set(as).size === 9;
  const consistent = (ac === gc) === (Number(A.argmax) === plan.genIndex(0, 12));
  if (resolved && consistent) ok(12, 'argmax ' + A.argmax + ' and the generating topology each canonicalise to 9 distinct splits; split and index comparisons agree; recovered=' + (ac === gc));
  else bad(12, 'canonicalisation: argmax ' + as.length + ' splits, generating ' + gs.length + ' splits, split/index comparisons ' + (consistent ? 'agree' : 'DISAGREE'));
  console.log('      (measured: argmax ' + (ac === gc ? 'IS' : 'is NOT') + ' the generating topology at n=12, 40 sites)');
}

// 013/014 - cross-method: the slow reference completes the ENTIRE space at n=9 and n=10
{
  const t0 = Date.now();
  const e9 = runInline(mkInst(mod), plan.SEED, plan.packP1(9, 0, 0), 512, 2);
  const r9 = runInline(ref, plan.SEED, plan.packP1(9, 0, 0), 512, 2);
  if (plan.fingerprint(e9) === plan.fingerprint(r9)) ok(13, 'n=9 end to end: full 135,135-tree enumeration, engine === reference');
  else bad(13, 'n=9 end-to-end disagreement');
  console.log('      (n=9 cross-method: ' + secs(Date.now() - t0) + ')');
}
{
  const t0 = Date.now();
  // Like against like: runInline reduces BOTH rounds into one accumulator
  // (visited counts every tree twice), runPooled merges per-round (once), and
  // this was the one assertion that crossed the two conventions: it compared
  // the runners' bookkeeping, not the implementations, and could not pass
  // (measured: visited 4,054,050 vs 2,027,025, all 25 hist bins equal). The
  // engine goes through the same pooled path as the reference.
  const e10 = await runPooled('wasm', plan.SEED, plan.packP1(10, 0, 0), 512, 2, threads);
  const r10 = await runPooled('ref', plan.SEED, plan.packP1(10, 0, 0), 512, 2, threads);
  if (plan.fingerprint(e10) === plan.fingerprint(r10)) ok(14, 'n=10 end to end: full 2,027,025-tree enumeration, engine === reference');
  else bad(14, 'n=10 end-to-end disagreement');
  console.log('      (n=10 cross-method: ' + secs(Date.now() - t0) + ')');
}

// 015 - the planted object: data regenerated down variant 1, same unmodified engine
{
  const e = runInline(mkInst(mod), plan.SEED, plan.packP1(9, 1, 0), 512, 2);
  const r = runInline(ref, plan.SEED, plan.packP1(9, 1, 0), 512, 2);
  const want = plan.genIndex(1, 9);
  // Same correction as 012: recovery of the generating tree was the spec's
  // hope, not the page's claim. The checkable truth is cross-implementation
  // agreement on the full record; the recovery outcome is reported.
  // Until 2026-09-26 this was ok(condition, message) and could not fail (ok takes a
  // number first); it now branches on the condition.
  if (plan.fingerprint(e) === plan.fingerprint(r))
    ok(15, 'planted data: engine and reference agree on the full variant-1 record (argmax ' + e.argmax + '; generating tree ' + want + '; recovered=' + (e.argmax === BigInt(want)) + ')');
  else bad(15, 'planted data: engine and reference DISAGREE on the variant-1 record (engine argmax ' + e.argmax + ', reference argmax ' + r.argmax + ')');
}

// 016 - the shipped page states what this verifier recomputes
{
  const html = readFileSync(path.join(DIR, 'index.html'), 'utf8');
  const checks = [
    [/654,729,075/, 'the 12-taxon tree count'],
    [/135,135/, 'the 9-taxon tree count'],
    [/2,027,025/, 'the 10-taxon tree count'],
    [/34,459,425/, 'the 11-taxon tree count'],
    [/20260825/, 'the stated seed'],
    [/40 simulated sites|40 sites/, 'the stated site count'],
    ['research/' + SLUG + '/verify-' + SLUG + '.mjs', 'the verifier path'],
    ['__deepReport', 'the machine-readable report hook'],
    ['/_kit/deep.js', 'the kit script tag']
  ];
  let htmlOk = true;
  for (const [pat, what] of checks) {
    const hit = typeof pat === 'string' ? html.includes(pat) : pat.test(html);
    if (!hit) { htmlOk = false; bad(16, 'page HTML missing ' + what); }
  }
  if (html.includes('\u2014')) { htmlOk = false; bad(16, 'page HTML contains an em dash'); }
  // every fixed figure, recomputed here and formatted the way the page prints it
  const figs = [[plan.treeCount(12), '654,729,075'], [plan.treeCount(9), '135,135'],
                [plan.treeCount(10), '2,027,025'], [plan.treeCount(11), '34,459,425']];
  for (const [val, lit] of figs) {
    if (val.toLocaleString('en-US') !== lit) { htmlOk = false; bad(16, 'figure ' + lit + ' does not recompute (' + val + ')'); }
  }
  if (htmlOk) ok(16, 'shipped HTML: every stated fixed figure recomputes, verifier path resolves, no em dashes');
}

// 017/018 - a THIRD likelihood, sharing no scoring code with engine.c or reference.js
// The battery (004) only asks the engine and the reference to agree with each other,
// and they share every modelling choice: until 2026-09-26 both added 150 ln 10 after
// rescaling instead of subtracting it, the battery stayed green, and the least likely
// trees at n=12 sorted to the top. naive-likelihood.mjs simulates the 40 sites from the
// stated contract and scores each site separately (pruning rooted at tip 0, and a
// brute-force sum over all internal-state assignments), summing per-site logs with no
// running product, no rescaling and no pattern compression. 017 asserts that on a
// handful of n=12 trees the engine AND the reference match it to 1e-9 in log-likelihood
// and rank the trees in the same order; 018 asserts that 017's test goes red on a copy
// of reference.js with the old sign error put back.
const TOL = 1e-9;
const STATED_ML = 222043168;              // the page's corrected maximum-likelihood tree
function modeOneScorer(impl) {
  return (i) => {
    impl.init(plan.SEED, plan.packP1(12, 0, 1));
    impl.putState(plan.stateWithIndex(i));
    const c = impl.chunk(0, 0, 1);
    return new DataView(c.out.buffer, c.out.byteOffset || 0, c.out.byteLength).getFloat64(16, true);
  };
}
const thirdTrees = (() => {
  const t = [STATED_ML, Number(A.argmax), plan.genIndex(0, 12), 245267729];  // 245267729: the old bug's top tree
  let s = 0x2026_0926 >>> 0;
  while (t.length < 12) {                 // eight more, from a fixed LCG, uniform over the space
    s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
    t.push(Math.floor((s / 4294967296) * N12));
  }
  return [...new Set(t)];
})();
const naiveSites = naive.simulate(12, 0);
const naiveL = new Map();
let naiveSelf = 0;
for (const i of thirdTrees) {
  const r = naive.naiveLogL(i, 12, 0, naiveSites);
  naiveSelf = Math.max(naiveSelf, Math.abs(r.byPruning - r.byBrute));
  naiveL.set(i, r.byPruning);
}
function thirdCheck(score) {
  let maxDiff = 0, flips = 0, pairs = 0;
  const got = new Map(thirdTrees.map((i) => [i, score(i)]));
  for (const i of thirdTrees) {
    const d = Math.abs(got.get(i) - naiveL.get(i));
    maxDiff = Math.max(maxDiff, Number.isNaN(d) ? Infinity : d);   // NaN or -Infinity scores count as failures
  }
  for (const i of thirdTrees) for (const j of thirdTrees) {
    if (i >= j) continue;
    const dn = naiveL.get(i) - naiveL.get(j);
    if (Math.abs(dn) <= TOL) continue;
    pairs++;
    if (Math.sign(got.get(i) - got.get(j)) !== Math.sign(dn)) flips++;
  }
  const bestOf = (m) => [...m.entries()].reduce((a, b) => (b[1] > a[1] ? b : a))[0];
  return { maxDiff, flips, pairs, sameBest: bestOf(got) === bestOf(naiveL), got };
}
{
  const bestNaive = [...naiveL.entries()].reduce((a, b) => (b[1] > a[1] ? b : a));
  const e = thirdCheck(modeOneScorer(mkInst(mod)));
  const r = thirdCheck(modeOneScorer(ref));
  const good = (c) => c.maxDiff <= TOL && c.flips === 0 && c.sameBest;
  if (naiveSelf <= TOL && good(e) && good(r) && bestNaive[0] === Number(A.argmax))
    ok(17, 'third likelihood on ' + thirdTrees.length + ' n=12 trees: engine within ' + e.maxDiff.toExponential(1) +
      ', reference within ' + r.maxDiff.toExponential(1) + ' (tol ' + TOL + '); all ' + e.pairs + ' pairwise orderings agree; best of the set is ' +
      bestNaive[0] + ' at ' + bestNaive[1].toFixed(4) + ' = the enumeration argmax');
  else bad(17, 'third likelihood: pruning vs brute force ' + naiveSelf.toExponential(1) + '; engine maxDiff ' + e.maxDiff.toExponential(1) +
    ' orderings flipped ' + e.flips + '/' + e.pairs + '; reference maxDiff ' + r.maxDiff.toExponential(1) + ' flipped ' + r.flips + '/' + r.pairs +
    '; naive best ' + bestNaive[0] + ' vs enumeration argmax ' + A.argmax);
}
{
  const bugSrc = refSrc.replace('scale -= 150.0 * 2.302585092994046', 'scale += 150.0 * 2.302585092994046');
  if (bugSrc === refSrc) bad(18, 'control: could not find the rescale line in reference.js to reintroduce the old sign error');
  else {
    const bp = path.join(TMP, 'reference-oldsign.mjs');
    writeFileSync(bp, bugSrc);
    const bugRef = await import(pathToFileURL(bp).href);
    const c = thirdCheck(modeOneScorer(bugRef));
    const red = c.maxDiff > TOL || c.flips > 0 || !c.sameBest;
    if (red) ok(18, 'control: reference.js with +150 ln 10 restored fails 017 (maxDiff ' + c.maxDiff.toFixed(2) + ', ' + c.flips + '/' + c.pairs + ' orderings flipped, best of set ' + (c.sameBest ? 'unchanged' : 'WRONG') + ')');
    else bad(18, 'control FAILED to trip: the old sign error passes the third-likelihood check');
  }
}

// ---------------------------------------------------------------- negative controls on THIS verifier
{
  const wrongRadix = (() => { let r = 1; for (let x = 3; x <= 2 * 12 - 7; x += 2) r *= x; return r; })();
  ctrl(1, 'mutating the radix to 2k-7 gives a visited total of ' + wrongRadix + ' != ' + N12 + ': assertion 011 would fail (detector armed)');
  const fp = plan.fingerprint(Object.assign(plan.initial(), { visited: 5, maxLogL: -12.5, argmax: 3 }));
  ctrl(2, 'flipping one character of a fingerprint (' + fp.slice(0, 12) + '...) makes the battery comparison unequal: assertion 004 would fail');
  const g1 = vGenCanon(0, 8);
  const g2 = vGenCanon(1, 8);
  ctrl(3, 'swapping the generating digit tuple changes the canonical form (' + (g1 !== g2 ? 'forms differ' : 'FORMS EQUAL, detector blind') + '): assertion 012 would fail on a wrong topology');
}

console.log('');
console.log(pass + ' passed, ' + fail + ' failed, ' + skip + ' skipped');
process.exit(fail > 0 ? 1 : 0);
