// verify-loschmidts-paradox.mjs: checks /strata/loschmidts-paradox/ against the engine and data the
// page actually serves, against independent reasoning written here, and against its own printed text.
//
//   node verify-loschmidts-paradox.mjs          # exactness, the laws of the map, seed 1 remeasured
//                                               # from scratch, every seed's rate, the page's numbers
//   node verify-loschmidts-paradox.mjs --full   # also remeasures all five seeds' horizons (several
//                                               # minutes: it is the same work measure.mjs did)
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads the page's engine.mjs, app.mjs, data/*.json and index.html from https://artwaste.land
// into ./loschmidts-paradox-files/ (the bytes your browser runs). Exit 0 = every check passed.

import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'loschmidts-paradox';
const FULL = process.argv.includes('--full');
const FILES = ['engine.mjs', 'app.mjs', 'data/results.json', 'data/posthoc-hiding.json', 'data/collisions.json', 'data/kelvin.json', 'index.html', 'research/PREREGISTRATION.md', 'research/PREREGISTRATION-KELVIN.md', 'research/FACTCHECK.md', 'research/sources/quotes.json', 'research/sources/README.md'];
let dir = join(here, 'public/strata', slug);
const inRepo = existsSync(join(dir, 'engine.mjs'));
if (!inRepo) {
  dir = resolve(`${slug}-files`);
  for (const f of FILES) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    mkdirSync(dirname(join(dir, f)), { recursive: true }); writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const R = JSON.parse(readFileSync(join(dir, 'data/results.json'), 'utf8'));
const PH = JSON.parse(readFileSync(join(dir, 'data/posthoc-hiding.json'), 'utf8'));
const KV = JSON.parse(readFileSync(join(dir, 'data/kelvin.json'), 'utf8'));
const COLL = JSON.parse(readFileSync(join(dir, 'data/collisions.json'), 'utf8'));
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const has2 = (s) => text.includes(s);
const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ');

let pass = 0, fail = 0;
function check(name, ok, detail = '') {
  if (ok) { pass++; console.log(`  ok   ${name}${detail ? '  (' + detail + ')' : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  (' + detail + ')' : ''}`); }
}
const slope = (xs, ys) => {
  const n = xs.length, mx = xs.reduce((a, b) => a + b) / n, my = ys.reduce((a, b) => a + b) / n;
  let sxy = 0, sxx = 0; for (let i = 0; i < n; i++) { sxy += (xs[i] - mx) * (ys[i] - my); sxx += (xs[i] - mx) ** 2; }
  return { slope: sxy / sxx, intercept: my - (sxy / sxx) * mx };
};

// ── A. the served engine is the research engine (inside the repository only) ──────────────────
if (inRepo) {
  const a = readFileSync(join(dir, 'engine.mjs'), 'utf8'), b = readFileSync(join(here, 'research/arrow-of-time/engine.mjs'), 'utf8');
  check('A1 the page serves research/arrow-of-time/engine.mjs byte for byte', a === b);
  const r2 = readFileSync(join(here, 'research/arrow-of-time/results.json'), 'utf8');
  for (const [served, src] of [['research/PREREGISTRATION.md', 'PREREGISTRATION.md'], ['research/PREREGISTRATION-KELVIN.md', 'PREREGISTRATION-KELVIN.md'], ['research/FACTCHECK.md', 'FACTCHECK.md'], ['research/sources/quotes.json', 'sources/quotes.json'], ['research/sources/README.md', 'sources/README.md']])
    check(`A3 the page serves research/arrow-of-time/${src} byte for byte`, readFileSync(join(dir, served), 'utf8') === readFileSync(join(here, 'research/arrow-of-time', src), 'utf8'));
  check('A2 the page serves research/arrow-of-time/results.json byte for byte', r2 === readFileSync(join(dir, 'data/results.json'), 'utf8'));
}

// ── B. the laws of the map, tested directly ──────────────────────────────────────────────────
console.log('B. the integer gas is exactly reversible');
{
  // B1: reversal is an involution (doing it twice changes nothing)
  const g = new E.IntGas(E.initial({ seed: 7 })); g.step(300);
  const k = g.key(); g.reverse(); g.reverse();
  check('B1 reversing twice is the identity, to the bit', g.key() === k);
  // B2: reverse, step, reverse undoes one step: R S R = S^-1, on a state in the middle of collisions
  const h = new E.IntGas(E.initial({ seed: 7 })); h.step(300);
  const before = h.key(); h.step(1); h.reverse(); h.step(1); h.reverse();
  check('B2 one step forward, reversed, one step, reversed: back to the bit', h.key() === before);
  // B3: the page's central claim, for each seed and three horizons
  let all = true, n = 0;
  for (const seed of [1, 2, 3, 4, 5]) for (const T of [500, 2000, 6000, 8000]) {
    const init = E.initial({ seed }), a = new E.IntGas(init), k0 = a.key();
    a.step(T); a.reverse(); a.step(T); a.reverse();
    all = all && a.key() === k0; n++;
  }
  check('B3 out T steps and back returns every one of 512 integers exactly', all, `${n} runs: seeds 1-5 x T = 500, 2000, 6000, 8000`);
  // B4: the NAIVE reversal (keep positions, flip velocities) is not the inverse of this map; a
  // mutant built that way must fail B3, or B3 would be testing nothing
  class Naive extends E.IntGas { reverse() { for (let i = 0; i < this.N; i++) { this.DX[i] = -this.DX[i]; this.DY[i] = -this.DY[i]; } } }
  const m = new Naive(E.initial({ seed: 1 })), mk = m.key(); m.step(500); m.reverse(); m.step(500); m.reverse();
  check('B4 mutant: flipping velocities in place (without the half step back) does NOT return exactly', m.key() !== mk);
  // B5: a mutant whose force is not rounded before it acts is no longer a map on integers, and the
  // return must break
  class Unrounded extends E.IntGas {
    step(n = 1) { const r = Math.round; Math.round = (x) => x; try { super.step(n); } finally { Math.round = r; } }
  }
  const u = new Unrounded(E.initial({ seed: 1 })), uk = u.key(); u.step(3000); u.reverse(); u.step(3000); u.reverse();
  check('B5 mutant: forces left unrounded, the return is no longer exact', u.key() !== uk);
  // B6: the floating gas, same everything, does not return exactly even over 500 steps
  const fi = E.initial({ seed: 1 }), f = new E.FloatGas(fi); f.step(500); f.reverse(); f.step(500); f.reverse();
  const ferr = E.maxSeparation(f.xs(), f.ys(), fi.x, fi.y);
  check('B6 the floating gas misses by a nonzero amount even at T = 500', ferr > 0 && ferr < 1e-9, `${ferr.toExponential(2)} of the box`);
}

// ── C. the gas is a physical gas: it spreads, and it conserves energy ────────────────────────
console.log('C. it behaves like a gas');
{
  const init = E.initial({ seed: 1 });
  const g = new E.IntGas(init), f = new E.FloatGas(init);
  const e0 = g.energy().e, f0 = f.energy().e; let gmax = 0, fmax = 0;
  for (let s = 0; s < 40; s++) { g.step(100); f.step(100); gmax = Math.max(gmax, Math.abs(g.energy().e / e0 - 1)); fmax = Math.max(fmax, Math.abs(f.energy().e / f0 - 1)); }
  let gall = gmax, fall = fmax;
  for (const seed of [2, 3, 4, 5]) {
    const ii = E.initial({ seed }), gg = new E.IntGas(ii), ff = new E.FloatGas(ii), ge = gg.energy().e, fe = ff.energy().e;
    for (let s = 0; s < 40; s++) { gg.step(100); ff.step(100); gall = Math.max(gall, Math.abs(gg.energy().e / ge - 1)); fall = Math.max(fall, Math.abs(ff.energy().e / fe - 1)); }
  }
  check('C1 integer gas energy within 0.6% over 4,000 steps, all five gases (as printed)', gall < 0.006 && has2('energy held within 0.6% over 4,000 steps'), `worst ${(gall * 100).toFixed(2)}%`);
  check('C2 floating gas energy within 0.04%, all five gases (as printed)', fall < 0.0004 && has2('the floating gas within 0.04%'), `worst ${(fall * 100).toFixed(3)}%`);
  const lf = E.leftFraction(g.xs());
  check('C3 after 4,000 steps the left-half share is near one half', Math.abs(lf - 0.5) < 0.1, `${(lf * 100).toFixed(1)}%`);
  // C4: running the START backwards also spreads: t = 0 is a minimum, not an edge
  const b = new E.IntGas(init); b.reverse(); b.step(1500);
  check('C4 the starting state run backwards in time also spreads out', E.leftFraction(b.xs()) < 0.75, `${(E.leftFraction(b.xs()) * 100).toFixed(1)}% left at t = -1,500`);
}

// ── D. results.json: its derived numbers follow from its raw ones ─────────────────────────────
console.log('D. the summary is arithmetic on the raw measurements');
{
  let ok = true;
  for (const r of R.rows) {
    const f = slope(R.KS, R.KS.map(k => r.horizons[k]));
    const pred = -1 / r.rateBitsPerStep;
    ok = ok && Math.abs(f.slope - r.stepsPerBitMeasured) < 1e-9 && Math.abs(pred - r.stepsPerBitPredicted) < 1e-9
      && Math.abs(f.slope / pred - r.ratio) < 1e-9 && r.pass === (Math.abs(f.slope / pred - 1) <= 0.25)
      && r.floatLaterThanK0 === (r.floatHorizon > r.horizons[0]);
  }
  check('D1 every slope, ratio and verdict in results.json recomputes', ok);
  const p2 = R.rows.filter(r => r.pass).length, p3 = R.rows.filter(r => r.floatLaterThanK0).length;
  check('D2 tallies: no-nudge never failed on all 5; slope held on 3; float later on 4', R.prediction1_noNudgeNeverFails && p2 === 3 && p3 === 4, `${p2}, ${p3}`);
}

// ── E. remeasure from scratch (seed 1 always; all five with --full) ──────────────────────────
console.log(`E. remeasured from scratch (${FULL ? 'all five seeds' : 'seed 1; --full for all five'})`);
function rateFor(seed) {
  const g = new E.IntGas(E.initial({ seed })); g.step(4000);
  const per = [];
  for (let d = 0; d < 8; d++) {
    const p = g.clone(), q = g.clone(); q.nudge(d, 1);
    const ts = [], bs = [];
    for (let s = 25; s <= 3000; s += 25) {
      p.step(25); q.step(25);
      const sep = E.maxSeparation(p.xs(), p.ys(), q.xs(), q.ys()) * E.L, b = sep > 0 ? Math.log2(sep) : -Infinity;
      if (b >= 8 && b <= 24) { ts.push(s); bs.push(b); }
    }
    per.push(ts.length >= 3 ? slope(ts, bs).slope : null);
  }
  const ok = per.filter(v => v != null); return ok.reduce((a, b) => a + b, 0) / ok.length;
}
function horizon(seed, kind, k, TMAX = 8000) {
  const init = E.initial({ seed }), g = kind === 'float' ? new E.FloatGas(init) : new E.IntGas(init);
  for (let T = 100; T <= TMAX; T += 100) {
    g.step(100); const r = g.clone();
    if (k != null) r.nudge(0, kind === 'float' ? 2 ** k / E.L : 2 ** k);
    r.reverse(); r.step(T); r.reverse();
    if (E.maxSeparation(r.xs(), r.ys(), init.x, init.y) > init.sigma) return T;
  }
  return null;
}
{
  const rc2 = 1.2599210498948732 * E.DEFAULTS.sigma ** 2;
  const g = new E.IntGas(E.initial({ seed: 1 })); g.step(4000);
  const inRange = () => { const s = new Set(); for (let i = 0; i < g.N; i++) for (let j = i + 1; j < g.N; j++) {
    let dx = (g.X[i] - g.X[j]) * E.H, dy = (g.Y[i] - g.Y[j]) * E.H; dx -= Math.round(dx); dy -= Math.round(dy);
    if (dx * dx + dy * dy < rc2) s.add(i * 1000 + j); } return s; };
  let prev = inRange(), starts = 0;
  for (let s = 0; s < 4000; s++) { g.step(1); const cur = inRange(); for (const p of cur) if (!prev.has(p)) starts++; prev = cur; }
  check('E0 seed 1: collisions counted again from scratch', starts === COLL.find(c => c.seed === 1).collisions, `${starts}`);
}
for (const row of R.rows) {
  const deep = FULL || row.seed === 1;
  const rate = rateFor(row.seed);
  check(`E${row.seed}a seed ${row.seed}: separation grows ${(rate * 1000).toFixed(2)} bits per 1,000 steps`, Math.abs(rate - row.rateBitsPerStep) < 1e-12);
  if (!deep) continue;
  const hs = R.KS.map(k => horizon(row.seed, 'int', k));
  check(`E${row.seed}b seed ${row.seed}: horizons for nudges 2^0..2^24 grid steps`, hs.every((T, i) => T === row.horizons[R.KS[i]]), hs.join(', '));
  const fh = horizon(row.seed, 'float', null);
  check(`E${row.seed}c seed ${row.seed}: floating-point horizon`, fh === row.floatHorizon, String(fh));
  const nh = horizon(row.seed, 'int', null);
  check(`E${row.seed}d seed ${row.seed}: with no nudge, never fails out to 8,000 steps`, nh === null && row.noNudgeFailed === null);
}

// ── F. the page says what the data say ──────────────────────────────────────────────────────
console.log('F. the page text');
{
  const has = (s) => text.includes(s);
  check('F1 the page states the prediction tallies (3 of 5, 4 of 5, 5 of 5)', has('held for 3 of the 5') && has('4 of the 5') && has('all 5'));
  const r1 = R.rows[0];
  check('F2 seed 1 horizons printed as measured', has(`${r1.horizons[0].toLocaleString('en-GB')} steps`) && has(`${r1.floatHorizon.toLocaleString('en-GB')}`));
  const ratios = R.rows.map(r => r.ratio.toFixed(2));
  check('F3 every seed\'s ratio is printed', ratios.every(x => has(x)), ratios.join(' '));
  check('F4 post-hoc hiding medians printed (k=0 and k=8)', has(`${PH['0'].median} steps`) && has(`${PH['8'].median} steps`), `${PH['0'].median}, ${PH['8'].median}`);
  check('F5 the post-hoc run is labelled as such on the page', /not pre-registered/i.test(text));
  const mRate = R.rows.map(r => r.rateBitsPerStep * 1000), lo = Math.min(...mRate).toFixed(1), hi = Math.max(...mRate).toFixed(1);
  check('F6 the rate range printed matches the five seeds', has(`${lo} to ${hi} bits`), `${lo} to ${hi}`);
  const cs = COLL.map(c => c.stepsBetweenCollisionsPerDisk);
  check('F8 the collision interval range printed matches', has(`${Math.round(Math.min(...cs))} to ${Math.round(Math.max(...cs))} steps`), `${Math.round(Math.min(...cs))} to ${Math.round(Math.max(...cs))}`);
  const mult = R.rows.map((r, i) => 2 ** (r.rateBitsPerStep * COLL.find(c => c.seed === r.seed).stepsBetweenCollisionsPerDisk));
  check('F9 the growth per collision printed matches rate x interval', has(`${Math.min(...mult).toFixed(1)} to ${Math.max(...mult).toFixed(1)} times`), mult.map(m => m.toFixed(2)).join(' '));
  const coll = Math.log(1 / (E.DEFAULTS.sigma * E.L)) / Math.log(1 / 3);
  check('F10 "about eighteen collisions": a factor of 3 per collision takes 1/(0.05 x 2^32) to 1 in ' + coll.toFixed(1), coll > 17 && coll < 19 && has('about eighteen collisions'));
  check('F11 one grid step is 0.047 nm for a 1 cm disk', (0.01 / (E.DEFAULTS.sigma * E.L) * 1e9).toFixed(3) === '0.047' && has('0.047 nanometres'));
  const KS4 = [4, 8, 12, 16, 20, 24];
  const refit = R.rows.map(r => slope(KS4, KS4.map(k => r.horizons[k])).slope / r.stepsPerBitPredicted);
  check('F12 post-hoc refit without the one-step point: ratios 0.63 to 0.85, three outside the band', Math.min(...refit).toFixed(2) === '0.63' && Math.max(...refit).toFixed(2) === '0.85' && refit.filter(x => Math.abs(x - 1) > 0.25).length === 3 && has('ratios of 0.63 to 0.85, three gases outside the band'));
  const eff = R.rows.map(r => r.floatEffectiveK);
  check('F13 float effective nudge printed as 2^-6 to 2^-30 of a grid step', Math.round(Math.max(...eff)) === -6 && Math.round(Math.min(...eff)) === -30 && has('between 2⁻⁶ and 2⁻³⁰ of a grid step'));
  const links = [...html.matchAll(/href="\.\/(research\/[^"]+)"/g)].map(m => m[1]);
  check('F14 every ./research/ link on the page is a served file this verifier read', links.length >= 4 && links.every(l => FILES.includes(l) && existsSync(join(dir, l))), links.join(' '));
  const app = readFileSync(join(dir, 'app.mjs'), 'utf8');
  check('F7 the page\'s instruments run this engine (app.mjs imports ./engine.mjs)', /from '\.\/engine\.mjs'/.test(app));
}

// ── G. Thomson's sentence, tested (PREREGISTRATION-KELVIN.md) ───────────────────────────────
console.log('G. Kelvin 1874 on the number of molecules');
{
  if (inRepo) check('G0 the page serves research/arrow-of-time/kelvin.json byte for byte', readFileSync(join(here, 'research/arrow-of-time/kelvin.json'), 'utf8') === readFileSync(join(dir, 'data/kelvin.json'), 'utf8'));
  const spear = (a, b) => { const rk = v => { const ix = v.map((x, i) => [x, i]).sort((p, q) => p[0] - q[0]), r = []; for (let i = 0; i < ix.length;) { let j = i; while (j + 1 < ix.length && ix[j + 1][0] === ix[i][0]) j++; for (let k = i; k <= j; k++) r[ix[k][1]] = (i + j) / 2; i = j + 1; } return r; };
    const x = rk(a), y = rk(b), n = a.length, mx = x.reduce((p, q) => p + q) / n, my = y.reduce((p, q) => p + q) / n; let sxy = 0, sxx = 0, syy = 0;
    for (let i = 0; i < n; i++) { sxy += (x[i] - mx) * (y[i] - my); sxx += (x[i] - mx) ** 2; syy += (y[i] - my) ** 2; } return sxy / Math.sqrt(sxx * syy); };
  const ok = KV.cells.every(c => Math.abs(spear(KV.NS, c.peak) - c.rhoPeak) < 1e-12 && Math.abs(spear(KV.NS, c.Dcoll) - c.rhoD) < 1e-12);
  check('G1 every rank correlation in kelvin.json recomputes from its own columns', ok);
  check('G2 K0 held; K1 9 of 9; K2 9 of 9 non-negative; K3 0 of 9 within the 1.5x bound', KV.K0 && KV.K1.negative === 9 && KV.K2.rhoNonNegative === 9 && KV.K3.within === 0);
  // G3: remeasure the two smallest gases for seed 1 from scratch (the large ones take minutes)
  for (const N of [32, 64]) {
    const sigma = 0.05 * Math.sqrt(128 / N), dt = 2.5e-4 * sigma / 0.05, init = E.initial({ seed: 1, N, sigma, dt }), g = new E.IntGas(init);
    let Teq = null; while (Teq === null) { g.step(10); if (E.leftFraction(g.xs()) <= 0.55) Teq = g.t; }
    const i = KV.NS.indexOf(N);
    check(`G3 seed 1, ${N} disks: equalises at ${Teq} steps as recorded`, Math.abs(Teq / KV.STEPS_PER_COLLISION - KV.sizes[i].TeqColl[0]) < 1e-12);
    const cell = KV.cells.find(c => c.seed === 1 && c.delta === 8);
    const p = g.clone(), r = E.rng(1001), amp = 2 ** -8 * sigma * E.L;
    for (let k = 0; k < N; k++) { p.X[k] = ((p.X[k] + Math.round((2 * r() - 1) * amp)) % E.L + E.L) % E.L; p.Y[k] = ((p.Y[k] + Math.round((2 * r() - 1) * amp)) % E.L + E.L) % E.L; }
    p.reverse(); let peak = -1, at = 0;
    for (let s = 0; s <= 2 * Teq; s += 10) { if (s) p.step(10); const f = E.leftFraction(p.xs()); if (f > peak) { peak = f; at = s; } }
    check(`G4 seed 1, ${N} disks, error 2^-8: peak share and its time reproduce`, peak === cell.peak[i] && Math.abs(at / KV.STEPS_PER_COLLISION - cell.Dcoll[i]) < 1e-12, `${peak}, ${at} steps`);
  }
  const m = a => a.reduce((x, y) => x + y) / a.length;
  const pk = (N, d) => (m(KV.cells.filter(c => c.delta === d).map(c => c.peak[KV.NS.indexOf(N)])) * 100).toFixed(1);
  check('G5 the page prints the 91.5% and 100% regained at error 2^-8', has2('between 91.5% (1,024 disks, the mean of three gases; the lowest single gas 91.4%) and 100% (up to 64 disks)') && (Math.min(...KV.cells.filter(c => c.delta === 8).map(c => c.peak[5])) * 100).toFixed(1) === '91.4' && pk(1024, 8) === '91.5' && pk(64, 8) === '100.0' && pk(32, 8) === '100.0');
  check('G6 the page prints 3.2 and 16.3 collisions to equalise', has2('(3.2 for 32 disks, 16.3 for 1,024)') && m(KV.sizes[0].TeqColl).toFixed(1) === '3.2' && m(KV.sizes[5].TeqColl).toFixed(1) === '16.3');
  const judged = KV.cells.filter(c => c.tstarRatio !== null);
  check('G8 K3 judgeable on 2 cells, failed on both (1.73, 1.83 > 1.5), as the page says', judged.length === 2 && judged.every(c => c.tstarRatio > 1.5) && has2('failed on both (1.73 and 1.83 times)') && judged.map(c => c.tstarRatio.toFixed(2)).join() === '1.73,1.83');
  // G7: Thomson's arithmetic. Odds against = 5^(2e12) x (5/4)^(8e12); its base-ten logarithm
  const lg = 2e12 * Math.log10(5) + 8e12 * Math.log10(5 / 4), lgK = (10 - 26 * Math.log10(2)) * 1e12;
  check('G7 Thomson\'s 2,173,220,000,000 digits: log10 of the odds is ' + (lg / 1e12).toFixed(5) + ' x 10^12, equal to his (10 - 26 log 2) x 10^12', Math.abs(lg - lgK) < 1e3 && Math.round(lg / 1e6) === 2173220 && has2('2,173,220,000,000'));
}

console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
