#!/usr/bin/env node
// verify-why-is-magnetism-quantum.mjs: checks /strata/why-is-magnetism-quantum/ ("The Crowd at the Wall").
//
//   node verify-why-is-magnetism-quantum.mjs            # engine, physics, and every figure the page states
//   node verify-why-is-magnetism-quantum.mjs --mutate   # also break the engine on purpose; checks must go red
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads the page's engine.mjs and index.html from https://artwaste.land into
// ./why-is-magnetism-quantum-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// What it checks:
//  A. the engine's mechanics: an electron's speed never changes (a magnetic force does no work);
//     a circle clear of the walls stays clear, and one that meets a wall keeps meeting one; the
//     time-averaged moment of the circling electrons equals the exact -v^2/(2B) per electron;
//  B. the physics the page shows: over twelve boxes at each of three fields the wall electrons
//     cancel the circling ones, the total scattering about zero as the standard error says it
//     should, while each half on its own is many standard errors from zero; the expected curve
//     (a one-dimensional integral) agrees with what the boxes draw; and the easy shortcut the
//     page warns against (mirroring a whole step at a wall) really does fail to cancel;
//  C. every figure the page states in prose, recomputed here and found in its text.
// What it does NOT check: the history (Bohr, van Leeuwen, Einstein and de Haas, the later
// measurements) or the quotations. Those were read against the sources the page lists, which are
// copied with the words relied on in assay/sources/why-is-magnetism-quantum.json.

import { existsSync, mkdirSync, writeFileSync, readFileSync } 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 = 'why-is-magnetism-quantum';
const MUTATE = process.argv.includes('--mutate');
const FILES = ['engine.mjs', 'index.html'];
let dir = process.env.AW_DIR || join(here, 'public/strata', slug);
const inRepo = !process.env.AW_DIR && existsSync(join(dir, 'engine.mjs'));
if (!process.env.AW_DIR && !inRepo) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  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}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);

const FIELDS = [0.1, 0.5, 2], SEEDS = 12, BOXES = FIELDS.length * SEEDS;
const MUTANTS = [
  ['a bounce off the left wall loses a tenth of the speed', 'if (x < 0) { x = 0; vx = Math.abs(vx); }', 'if (x < 0) { x = 0; vx = 0.9 * Math.abs(vx); }'],
  ['moment loses its factor of one half', 'return 0.5 * Q * (', 'return 1.0 * Q * ('],
  ['circling electrons counted as wall electrons', 'S.edge[i] = meetsWall(S, i) ? 1 : 0;', 'S.edge[i] = meetsWall(S, i) || i % 7 === 0 ? 1 : 0;'],
  ['wrong clearance probability', '(1 - v / vmax) ** 2', '(1 - v / vmax)'],
  ['time average divides by the wrong count', 'const k = Math.max(1, S.samples);', 'const k = Math.max(1, S.samples + 50);'],
];
async function checks(engineUrl, html, quiet = false) {
  const E = await import(engineUrl);
  let pass = 0, fail = 0;
  const ok = (cond, label) => {
    if (cond) { pass++; if (!quiet) console.log('  ok   ' + label); }
    else { fail++; if (!quiet) console.log('  FAIL ' + label); }
  };
  const text = html
    .replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
    .replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&middot;/g, '·').replace(/&amp;/g, '&')
    .replace(/&minus;/g, '−').replace(/&times;/g, '×').replace(/\s+/g, ' ');
  const says = (s) => text.includes(s);

  // ---- A. mechanics ----
  if (!quiet) console.log('A. the engine');
  {
    const S = E.makeBox({ N: 4000, B: 0.5, seed: 7 });
    const v0 = Float64Array.from({ length: S.N }, (_, i) => Math.hypot(S.vx[i], S.vy[i]));
    const kind0 = Uint8Array.from(S.edge);
    for (let k = 0; k < 600; k++) E.step(S, 0.05);
    let dv = 0, inside = true, stayed = true;
    for (let i = 0; i < S.N; i++) {
      dv = Math.max(dv, Math.abs(Math.hypot(S.vx[i], S.vy[i]) - v0[i]));
      if (S.x[i] < -1e-9 || S.x[i] > S.L + 1e-9 || S.y[i] < -1e-9 || S.y[i] > S.L + 1e-9) inside = false;
      if (!kind0[i] && E.meetsWall(S, i)) stayed = false;
    }
    ok(dv < 1e-9, `speeds unchanged after 600 steps (largest change ${dv.toExponential(1)})`);
    ok(inside, 'every electron still inside the box');
    ok(stayed, 'every circle that was clear of the walls is still clear');
    let still = 0, n = 0;
    for (let i = 0; i < S.N; i++) if (kind0[i]) { n++; if (E.meetsWall(S, i)) still++; }
    ok(still === n, `every circle that met a wall still meets one (${still} of ${n})`);
  }
  {
    const { avg, pred } = E.run({ N: 6000, B: 1, seed: 3, steps: 1500 });
    const rel = Math.abs(avg.bulk - pred.moment) / Math.abs(pred.moment);
    ok(rel < 0.01, `circling electrons, time-averaged ${avg.bulk.toFixed(0)} against exact -v²/2B summed ${pred.moment.toFixed(0)} (${(100 * rel).toFixed(2)}% apart)`);
  }

  // ---- B. the physics ----
  if (!quiet) console.log('B. the cancellation');
  const zs = [];
  for (const B of FIELDS) {
    let worstRatio = 0, smallestHalf = Infinity;
    for (let seed = 1; seed <= SEEDS; seed++) {
      const { avg } = E.run({ N: 5000, B, seed, steps: 1200 });
      zs.push(avg.total / avg.se);
      worstRatio = Math.max(worstRatio, Math.abs(avg.total) / Math.abs(avg.bulk));
      smallestHalf = Math.min(smallestHalf, Math.abs(avg.bulk) / avg.se, Math.abs(avg.edge) / avg.se);
    }
    ok(smallestHalf > 8, `B = ${B}: each half on its own is at least ${smallestHalf.toFixed(1)} standard errors from zero`);
    ok(worstRatio < 0.25, `B = ${B}: the wall electrons cancel the circling ones in all 12 boxes (largest leftover ${(100 * worstRatio).toFixed(1)}% of the circling moment)`);
  }
  const mz = zs.reduce((a, b) => a + b, 0) / zs.length;
  const rms = Math.sqrt(zs.reduce((a, b) => a + b * b, 0) / zs.length);
  ok(Math.abs(mz) < 3 / Math.sqrt(zs.length), `36 boxes: the total's mean is ${mz.toFixed(2)} standard errors from zero (a real moment would sit many away)`);
  ok(rms > 0.3 && rms < 1.6, `36 boxes: the totals scatter by ${rms.toFixed(2)} standard errors (about 1 if the ± is honest)`);
  {
    for (const B of [0.1, 0.3, 1, 3]) {
      const S = E.makeBox({ N: 20000, B, seed: 11 });
      const p = E.bulkPrediction(S), e = E.expectedBulk(B);
      const share = p.count / S.N, seShare = Math.sqrt(e.share * (1 - e.share) / S.N);
      ok(Math.abs(share - e.share) < 4 * seShare, `B = ${B}: share circling ${share.toFixed(4)} drawn, ${e.share.toFixed(4)} from the integral`);
      const per = p.moment / S.N;
      ok(Math.abs(per - e.perElectron) < 0.03 * Math.abs(e.perElectron) + 0.01, `B = ${B}: circling moment per electron ${per.toFixed(3)} drawn, ${e.perElectron.toFixed(3)} from the integral`);
    }
    // at strong field nearly every electron circles and each gives -kT/B, so the curve tends to -1/B
    const e = E.expectedBulk(30);
    ok(Math.abs(e.perElectron * 30 + 1) < 0.05, `strong field: moment per electron x B = ${(e.perElectron * 30).toFixed(3)}, tending to -1 (every electron circling, each -kT/B)`);
  }
  {
    // the shortcut the page warns against: move along the circle for a whole step, then mirror
    // whatever landed outside. The mirror image of a path in a field curls the wrong way.
    const S = E.makeBox({ N: 5000, B: 1, seed: 5 });
    const w = S.w, dt = 0.05, c = Math.cos(w * dt), s = Math.sin(w * dt), L = S.L;
    let aB = 0, aE = 0, n = 0;
    const measure = () => { const m = E.sample(S); aB += m.bulk; aE += m.edge; n++; };
    measure();
    for (let k = 0; k < 4000; k++) {
      for (let i = 0; i < S.N; i++) {
        const cx = S.x[i] + S.vy[i] / w, cy = S.y[i] - S.vx[i] / w;
        const nvx = S.vx[i] * c + S.vy[i] * s, nvy = -S.vx[i] * s + S.vy[i] * c;
        S.x[i] = cx - nvy / w; S.y[i] = cy + nvx / w; S.vx[i] = nvx; S.vy[i] = nvy;
        if (S.x[i] < 0) { S.x[i] = -S.x[i]; S.vx[i] = -S.vx[i]; } else if (S.x[i] > L) { S.x[i] = 2 * L - S.x[i]; S.vx[i] = -S.vx[i]; }
        if (S.y[i] < 0) { S.y[i] = -S.y[i]; S.vy[i] = -S.vy[i]; } else if (S.y[i] > L) { S.y[i] = 2 * L - S.y[i]; S.vy[i] = -S.vy[i]; }
      }
      measure();
    }
    const exact = E.run({ N: 5000, B: 1, seed: 5, steps: 4000 }).avg;
    const shortcutLeft = Math.abs(aB + aE) / Math.abs(aB), exactLeft = Math.abs(exact.total) / Math.abs(exact.bulk);
    ok(shortcutLeft > 3 * exactLeft && shortcutLeft > 0.1, `negative control: the mirror-the-step shortcut leaves ${(100 * shortcutLeft).toFixed(0)}% of the circling moment uncancelled, the exact bounce ${(100 * exactLeft).toFixed(1)}%`);
  }

  // ---- C. the page's figures ----
  if (!quiet) console.log('C. the page');
  const e1 = E.expectedBulk(1);
  const pct = (x, d = 0) => (100 * x).toFixed(d);
  ok(says(`${pct(e1.share)} per cent of the electrons`), `B = 1: "${pct(e1.share)} per cent of the electrons" circle clear of the walls (integral ${e1.share.toFixed(4)})`);
  const peak = (() => { let best = [0, 0]; for (let k = 0; k <= 4000; k++) { const B = Math.pow(10, -2 + 3 * k / 4000); const m = E.expectedBulk(B).perElectron; if (m < best[1]) best = [B, m]; } return best; })();
  ok(says(`near B = ${peak[0].toFixed(2)}`) && says(`${Math.abs(peak[1]).toFixed(2)} per electron`),
    `the circling moment is largest near B = ${peak[0].toFixed(2)}, at ${peak[1].toFixed(2)} per electron`);
  const d = E.DEFAULT;
  ok(says(`side ${d.L}`), `the box: side ${d.L}`);
  // every place the page (text, headings, meta and share descriptions) gives the number of electrons
  const counts = [...html.matchAll(/(?:(\d{1,3}(?:,\d{3})+)\s+(?:classical\s+)?electrons|box of (\d{1,3}(?:,\d{3})+)|Watch (\d{1,3}(?:,\d{3})+) of them)/g)]
    .map((m) => +(m[1] || m[2] || m[3]).replace(/,/g, ''));
  ok(counts.length >= 8 && counts.every((n) => n === d.N), `all ${counts.length} statements of the electron count say ${d.N} (found: ${[...new Set(counts)].join(', ')})`);
  ok(says(`over ${BOXES} boxes`), `"over ${BOXES} boxes": the verifier runs ${BOXES}`);
  ok(says(`breaks the engine ${['zero','one','two','three','four','five','six','seven','eight'][MUTANTS.length]} ways`), `"breaks the engine ${MUTANTS.length} ways": the verifier has ${MUTANTS.length} mutants`);
  ok(says(`other ${['zero','one','two','three','four','five','six','seven','eight','nine','ten'][100 - +pct(e1.share)]} per cent are the orange`),
    `B = 1: the other ${100 - +pct(e1.share)} per cent meet a wall`);
  // the slider: its starting value must be B = 1 (the figures above), its weakest setting the one the prose quotes
  const slider = html.match(/<input id="field"[^>]*>/)[0];
  const attr = (k) => +slider.match(new RegExp(`${k}="([^"]+)"`))[1];
  ok(attr('value') === 0, `the slider starts at B = 10^${attr('value')} = 1`);
  const Bweak = Math.pow(10, attr('min')), ew = E.expectedBulk(Bweak);
  ok(says(`weakest setting only ${pct(ew.share)} per cent`), `the slider's weakest setting, B = ${Bweak.toFixed(4)}: "only ${pct(ew.share)} per cent" circle clear (integral ${ew.share.toFixed(4)})`);
  // the number line: 2m/e from CODATA 2018, in grams per abcoulomb, and its half
  const ME = 9.1093837015e-28, E_EMU = 1.602176634e-20;
  ok(html.includes('ME = 9.1093837015e-28') && html.includes('E_EMU = 1.602176634e-20'), 'the number line uses the CODATA 2018 electron mass (g) and charge (abC)');
  const orbit = 2 * ME / E_EMU / 1e-7;
  ok(Math.abs(orbit - 1.1371) < 1e-4 && Math.abs(orbit / 2 - 0.57) < 0.005, `2m/e = ${orbit.toFixed(4)} x 10^-7, half of it ${(orbit / 2).toFixed(4)}: the later measurements' 0.57 is the spin value`);
  const num = (name) => { const m = html.match(new RegExp(`\\b${name} = ([0-9.]+)`)); return m ? +m[1] : NaN; };
  const measured = num('measured'), band = num('band'), later = num('later');
  ok(measured === 1.1 && says('λ = 1,1 . 10'), `the number line's 1915 value (${measured}) is the one quoted from the paper, "λ = 1,1"`);
  ok(band === 0.1 && says('a greater precision than of 10%'), `the number line's band (${band}) is the paper's 10%`);
  ok(later === 0.57 && says('shown the value of λ to be 0.57'), `the number line's later value (${later}) is Frenkel's 0.57`);
  const theory = 1.13;
  ok(says(`which they put at ${theory.toFixed(2)} × 10`) && says(`the theoretical one ${theory.toFixed(2).replace('.', ',')}.`), `the prose's ${theory} is the paper's printed "1,13"`);
  ok(Math.abs(theory - orbit) / orbit < 0.01, `1915's theoretical ${theory} is within 1% of today's 2m/e (${orbit.toFixed(3)})`);
  ok(measured * (1 - band) < orbit && orbit < measured * (1 + band) && orbit / 2 < measured * (1 - band) && Math.abs(later - orbit / 2) < 0.005,
    `${measured} with ${100 * band}% contains 2m/e and excludes m/e; ${later} is m/e`);
  // the ratio 'half' (Frenkel) and the arithmetic 'four years after Bohr's thesis', 'ten years after the rod turned'
  ok(says('four years after Bohr\'s thesis') && 1915 - 1911 === 4, '1915 is four years after 1911');
  ok(says('ten years after the rod turned') && 1925 - 1915 === 10, '1925 is ten years after 1915');
  ok(says('two years before his theory of the hydrogen spectrum') && 1913 - 1911 === 2, '1913 is two years after 1911');
  return { pass, fail };
}

const html = readFileSync(join(dir, 'index.html'), 'utf8');
const engineUrl = pathToFileURL(join(dir, 'engine.mjs')).href;
const { pass, fail } = await checks(engineUrl, html);
console.log(`\n${pass} passed, ${fail} failed`);

let mutFail = 0;
if (MUTATE) {
  const { mkdtempSync, rmSync } = await import('node:fs');
  const { tmpdir } = await import('node:os');
  const src = readFileSync(join(dir, 'engine.mjs'), 'utf8');
  const mutants = MUTANTS;
  console.log('\nmutants (each must turn at least one check red):');
  for (const [name, a, b] of mutants) {
    if (!src.includes(a)) { console.log(`  FAIL mutant "${name}" does not apply`); mutFail++; continue; }
    const tmp = mkdtempSync(join(tmpdir(), 'aw-mut-'));
    writeFileSync(join(tmp, 'engine.mjs'), src.replace(a, b));
    const r = await checks(pathToFileURL(join(tmp, 'engine.mjs')).href + '?m=' + Math.random(), html, true);
    rmSync(tmp, { recursive: true, force: true });
    if (r.fail > 0) console.log(`  ok   "${name}": ${r.fail} check(s) red`);
    else { console.log(`  FAIL "${name}": nothing noticed`); mutFail++; }
  }
}
process.exit(fail || mutFail ? 1 : 0);
