#!/usr/bin/env node
// verify-why-are-basalt-columns-hexagonal.mjs: checks /strata/why-are-basalt-columns-hexagonal/.
//
//   node verify-why-are-basalt-columns-hexagonal.mjs            # the geometry, the counts, the rock data, and every figure the page states
//   node verify-why-are-basalt-columns-hexagonal.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, sites.mjs and index.html from https://artwaste.land into
// ./why-are-basalt-columns-hexagonal-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// What it checks:
//  A. the crack networks: every cell a simple polygon, the areas summing to the square, and the corner
//     count equal to 3Y + 2T + 2B + 4 on every network, before and after junctions are pulled into Ys;
//  B. that a network made only of T junctions averages exactly 4 corners, whatever its size or seed;
//  C. the Voronoi cells on a torus: areas summing to 1, mean sides exactly 6 on every draw, and the
//     random-point hexagon share and spread against the published values for the plane;
//  D. the measured rock counts: each total and share recomputed from the transcribed table;
//  E. every figure the prose quotes, recomputed here and found in its own sentence on the page;
//  F. the plain square (no wrap): sides summing to 6n - k - 2 on every draw, and the frame count k + 4
//     against (8*sqrt(2)/pi) sqrt(n), the folding argument on the page (added 2026-11-02).
// What it does NOT check: that the sources say what the tables say they say. The words relied on,
// with the URL and the date each was fetched, are in assay/sources/why-are-basalt-columns-hexagonal.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-are-basalt-columns-hexagonal';
const MUTATE = process.argv.includes('--mutate');
const FILES = ['engine.mjs', 'sites.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}`);

let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) pass++; else { fail++; console.log(`FAIL ${msg}`); } return cond; };

async function run(E, SITES, RECOUNTS, html, quiet) {
  const before = fail;
  const say = (m) => { if (!quiet) console.log(m); };

  // A + B. crack networks
  for (const [m, seed] of [[1, 1], [10, 2], [60, 3], [120, 1], [250, 5], [400, 9]]) {
    const net = E.crackNetwork(m, seed);
    const t = E.tally(net);
    const A = net.cells.reduce((s, _, c) => s + E.area(net, c), 0);
    ok(t.F === m + 1, `network m=${m} seed=${seed}: ${t.F} cells, expected ${m + 1}`);
    ok(Math.abs(A - 1) < 1e-9, `network m=${m}: areas sum to ${A}`);
    ok(net.cells.every((_, c) => E.simple(net, c) && E.area(net, c) > 0), `network m=${m}: a cell is not a simple counter-clockwise polygon`);
    ok(t.Y === 0, `network m=${m}: ${t.Y} Y junctions before any are pulled`);
    ok(t.C === 4 * t.F, `network m=${m}: ${t.C} corners on ${t.F} cells, not 4 each on average`);
    ok(E.predictedCorners(t) === t.C, `network m=${m}: 3Y+2T+2B+4 = ${E.predictedCorners(t)} but ${t.C} counted`);
    ok(2 * m === t.T + t.frame, `network m=${m}: ${t.T} T + ${t.frame} frame junctions, expected 2 per crack (${2 * m})`);
    // pull junctions one at a time; the identity must hold after every pull
    const R = E.rng(seed * 7);
    let pulls = 0, held = true, simple = true;
    for (let k = 0; k < 5000; k++) {
      const J = E.junctions(net);
      if (!J.T.length) break;
      E.pullToY(net, J.T[Math.floor(R() * J.T.length)]); pulls++;
      const u = E.tally(net);
      if (E.predictedCorners(u) !== u.C) held = false;
      if (k % 25 === 0 && !net.cells.every((_, c) => E.simple(net, c) && E.area(net, c) > 0)) simple = false;
    }
    const u = E.tally(net);
    const A2 = net.cells.reduce((s, _, c) => s + E.area(net, c), 0);
    ok(held, `network m=${m}: 3Y+2T+2B+4 failed after some pull`);
    ok(simple && net.cells.every((_, c) => E.simple(net, c) && E.area(net, c) > 0), `network m=${m}: pulling made a cell cross itself`);
    ok(Math.abs(A2 - 1) < 1e-9, `network m=${m}: areas after pulling sum to ${A2}`);
    ok(u.T === 0, `network m=${m}: ${u.T} T junctions left after pulling all`);
    ok(u.C === 3 * u.Y + 2 * u.frame + 4, `network m=${m}: all-Y count ${u.C} != 3Y+2B+4`);
    say(`  cracks m=${m} seed=${seed}: ${t.F} cells, mean ${t.mean.toFixed(3)} corners; all pulled to Y (${pulls} pulls): mean ${u.mean.toFixed(3)}, ${u.frame} frame junctions`);
  }
  // corner identity must be what corners() counts, not something that could agree by accident:
  // a network's corner count computed a second, independent way (angles from atan2)
  {
    const net = E.crackNetwork(80, 4);
    const R = E.rng(3);
    for (let k = 0; k < 60; k++) { const J = E.junctions(net); if (!J.T.length) break; E.pullToY(net, J.T[Math.floor(R() * J.T.length)]); }
    let C2 = 0;
    for (const p of net.cells) for (let i = 0; i < p.length; i++) {
      const a = net.V[p[(i - 1 + p.length) % p.length]], b = net.V[p[i]], d = net.V[p[(i + 1) % p.length]];
      const ang = Math.atan2(d.y - b.y, d.x - b.x) - Math.atan2(b.y - a.y, b.x - a.x);
      const w = Math.atan2(Math.sin(ang), Math.cos(ang));
      if (Math.abs(w) > 1e-9) C2++;
    }
    ok(C2 === E.tally(net).C, `corner count by atan2 ${C2} != engine ${E.tally(net).C}`);
  }

  // C. Voronoi on a torus
  let hexSum = 0, muSum = 0, draws = 0;
  for (const seed of [1, 2, 3, 4, 5, 6, 7, 8]) {
    const P = E.poissonPoints(3000, seed);
    const cells = E.voronoiTorus(P);
    const s = E.stats(cells.map((c) => c.sides));
    const A = cells.reduce((acc, c) => { let a = 0; for (let i = 0; i < c.poly.length; i++) { const p = c.poly[i], q = c.poly[(i + 1) % c.poly.length]; a += p.x * q.y - q.x * p.y; } return acc + a / 2; }, 0);
    ok(Math.abs(A - 1) < 1e-9, `voronoi seed=${seed}: areas sum to ${A}`);
    ok(cells.reduce((t, c) => t + c.sides, 0) === 6 * cells.length, `voronoi seed=${seed}: sides sum to ${cells.reduce((t, c) => t + c.sides, 0)}, not 6 x ${cells.length}`);
    hexSum += s.hex; muSum += s.mu2; draws++;
  }
  const hex = hexSum / draws, mu2 = muSum / draws;
  say(`  random points, 8 x 3000 cells: hexagons ${(hex * 100).toFixed(2)}%, spread mu2 ${mu2.toFixed(3)}`);
  ok(Math.abs(hex - E.POISSON_HEX) < 0.01, `random-point hexagon share ${hex} far from the published ${E.POISSON_HEX}`);
  // each share against Calka's table (his are Monte Carlo too; 24,000 cells give about +-0.003)
  {
    const all = [];
    for (const seed of [1, 2, 3, 4, 5, 6, 7, 8]) all.push(...E.voronoiTorus(E.poissonPoints(3000, seed)).map((c) => c.sides));
    const st = E.stats(all);
    for (const [k, v] of Object.entries(E.CALKA)) ok(Math.abs((st.hist[k] || 0) / st.n - v) < 0.008, `share of ${k}-sided cells ${((st.hist[k] || 0) / st.n).toFixed(4)} vs Calka ${v}`);
  }
  for (const seed of [1, 2]) {
    const cells = E.voronoiTorus(E.hardcorePoints(2000, 0.45, seed));
    ok(cells.reduce((t, c) => t + c.sides, 0) === 6 * cells.length, `hard-core voronoi seed=${seed}: sides do not average 6`);
  }


  // D. the measured rock counts, against the totals and means their sources print
  const hs = SITES.find((x) => x.id === 'hetenyi');
  const hn = Object.values(hs.counts).reduce((a, b) => a + b, 0), hsum = Object.entries(hs.counts).reduce((a, [k, v]) => a + k * v, 0);
  ok(hn === 3033, `Hetenyi Fig. 7 counts sum to ${hn}, the caption says 3,033`);
  ok(hsum === 17312, `Hetenyi sum of sides ${hsum}, Table 4's total is 17,312`);
  ok(Math.abs(hsum / hn - hs.printedMean) < 0.005, `Hetenyi mean ${hsum / hn} vs printed ${hs.printedMean}`);
  for (const id of ['oreilly', 'oreilly-line', 'dike']) {
    const x = SITES.find((y) => y.id === id), tot = Object.values(x.pct).reduce((a, b) => a + b, 0);
    ok(Math.abs(tot - 100) < 0.05, `${id}: Sosman's percentages sum to ${tot}`);
  }
  const lee = SITES.find((x) => x.id === 'garibaldi'), leeN = Object.values(lee.counts).reduce((a, b) => a + b, 0);
  ok(leeN === 199 && lee.printedTotal === 200, `Lee's rows sum to ${leeN} (page says 199, printed total 200)`);
  for (const r of RECOUNTS) {
    const n = Object.values(r.counts).reduce((a, b) => a + b, 0), m = Object.entries(r.counts).reduce((a, [k, v]) => a + k * v, 0) / n;
    ok(Math.abs(m - r.printedMean) < 0.006, `recount ${r.user}: mean ${m.toFixed(3)} vs printed ${r.printedMean}`);
  }
  // calka's table sums to (almost) 1 and the engine carries it as printed
  const ck = Object.values(E.CALKA).reduce((a, b) => a + b, 0);
  ok(ck > 0.99 && ck <= 1, `Calka's k=3..9 shares sum to ${ck}`);

  // E. every figure the prose states, recomputed and found in its own sentence
  const text = html.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>/g, ' ').replace(/<\/t[dh]>/g, ' ').replace(/<[^>]+>/g, '').replace(/&amp;/g, '&').replace(/&#39;/g, "'").replace(/\s+/g, ' ');
  const sentences = text.split(/(?<=[.:;!?])\s+(?=[A-Z(“])/);
  const said = (fig, ...words) => ok(sentences.some((s) => s.includes(fig) && words.every((w) => s.includes(w))), `page does not state ${fig} beside ${words.join(', ')}`);
  const pct = (x) => (x * 100).toFixed(1) + '%';
  const p0 = E.spread(0), p45 = E.spread(0.45), p50 = E.spread(0.5);
  // pinned to words that occur only in each figure's own sentence (a claims pass found looser anchors
  // satisfied by a neighbouring sentence or by the table header)
  said(`reach ${pct(p45.hex)} at 45% and ${pct(p50.hex)} at 50%`);
  said(`hexagons in ${pct(p50.hex)} of cells`, 'At 50%');
  said(`(the standard deviation of the number of sides) of ${p50.sigma.toFixed(2)}`);
  said('The average never moves off 6.000');
  ok(E.voronoiTorus(E.hardcorePoints(400, 0.5, 3)).reduce((t, c) => t + c.sides, 0) === 6 * 400, 'the instrument-sized scatter does not average 6.000');
  said('32 of the 50 sites', '3,033');
  ok(text.includes(`${pct(p0.hex)} ${p0.sigma.toFixed(2)}`), `random-point row ${pct(p0.hex)} ${p0.sigma.toFixed(2)} not in the table`);
  ok(text.includes(`${pct(p50.hex)} ${p50.sigma.toFixed(2)}`), `disc row ${pct(p50.hex)} ${p50.sigma.toFixed(2)} not in the table`);
  const net = E.crackNetwork(300, 1), R2 = E.rng(31);
  for (let k = 0; k < 5000; k++) { const J = E.junctions(net); if (!J.T.length) break; E.pullToY(net, J.T[Math.floor(R2() * J.T.length)]); }
  const tl = E.tally(net);
  said(`into ${tl.F} cells`, 'Cracked 300 times'); said(tl.mean.toFixed(2), 'rather than 6');
  const S = Object.fromEntries(SITES.map((x) => [x.id, summaryOf(x)]));
  for (const x of SITES) {
    const m = S[x.id];
    ok(text.includes(`${m.n.toLocaleString('en-GB')} ${m.mean.toFixed(2)} ${pct(m.hex)} ${m.sigma.toFixed(2)}`), `table row for ${x.id} (${m.n} ${m.mean.toFixed(2)} ${pct(m.hex)} ${m.sigma.toFixed(2)}) not on the page`);
  }
  said('50.5%', '24.8%', '19.2%', '3.5%', '2.0%', '206'); 
  said('1,502 hexagons', '1,028 pentagons', '352 heptagons', '128 quadrilaterals', '23 octagons', '3,033');
  said(S.oreilly.mean.toFixed(2), S.hetenyi.mean.toFixed(2), 'average');
  said(`(${(S.hetenyi.t * 100).toFixed(1)}%)`, 'one junction in seven'); ok(Math.round(1 / S.hetenyi.t) === 7, `one in ${1 / S.hetenyi.t}`);
  said(`(${(S.oreilly.t * 100).toFixed(1)}%)`, 'one in twenty-three'); ok(Math.round(1 / S.oreilly.t) === 23, `one in ${1 / S.oreilly.t}`);
  said(`average ${S.garibaldi.mean.toFixed(2)} sides`, '199 columns'); said(`averages ${S.dike.mean.toFixed(2)}`, 'dike');
  ok(S.garibaldi.t > 0.5 && S.dike.t > 0.5, 'Garibaldi and the dike are not more than half Ts by the formula');
  const rm = RECOUNTS.map((r) => Object.entries(r.counts).reduce((a, [k, v]) => a + k * v, 0) / Object.values(r.counts).reduce((a, b) => a + b, 0));
  said(`from ${Math.min(...rm).toFixed(2)} to ${Math.max(...rm).toFixed(2)}`, 'six counts');
  const beta = RECOUNTS[0], phi1 = RECOUNTS[2];
  const nOf = (r) => Object.values(r.counts).reduce((a, b) => a + b, 0);
  said(`${beta.counts[6]} hexagons among ${nOf(beta)} columns`, `${phi1.counts[6]} among ${nOf(phi1)}`);
  said(String(E.CALKA[6]), 'six sides'); said(`(${E.CALKA[5]})`, 'pentagons');
  said('24,000 random points'); ok(8 * 3000 === 24000, '8 x 3000');
  said('14.6', 'ours'); // the arithmetic is labelled as ours

  // F. the plain square (added 2026-11-02): the same points with no wrap. Sides sum to 6n - k - 2
  // exactly, k the points where walls meet the frame, and k + 4 (the four per-side counts summed)
  // grows like (8*sqrt(2)/pi) * sqrt(n). Not repeated under --mutate: it does not use the engine's cells.
  if (!quiet) {
    const C = 8 * Math.SQRT2 / Math.PI;
    let a600 = 0;
    for (const [n, runs] of [[150, 40], [600, 20], [2400, 4]]) {
      let sk = 0, sa = 0, exact = 0;
      for (let s = 1; s <= runs; s++) {
        const R = E.rng(9000 + 10 * n + s), P = Array.from({ length: n }, () => ({ x: R(), y: R() }));
        const cells = voronoiSquare(P), sides = cells.reduce((t, c) => t + c.length, 0), k = framePoints(cells);
        ok(Math.abs(cells.reduce((t, c) => t + polyArea(c), 0) - 1) < 1e-9, `plain square n=${n} seed=${s}: areas do not sum to 1`);
        if (sides === 6 * n - k - 2) exact++;
        sk += k; sa += sides / n;
      }
      ok(exact === runs, `plain square n=${n}: 6n - k - 2 held on ${exact} of ${runs} scatters`);
      const law = (sk / runs + 4) / Math.sqrt(n);
      ok(Math.abs(law - C) < 0.15, `plain square n=${n}: (k + 4)/sqrt(n) = ${law.toFixed(3)}, not near 8*sqrt(2)/pi = ${C.toFixed(3)}`);
      if (n === 600) a600 = sa / runs;
      say(`  plain square, ${n} points, ${runs} scatters: mean sides ${(sa / runs).toFixed(3)}, (k + 4)/sqrt(n) ${law.toFixed(3)} (8*sqrt(2)/pi = ${C.toFixed(3)})`);
    }
    ok(a600.toFixed(2) === '5.85' || a600.toFixed(2) === '5.86', `600 plain-square points average ${a600.toFixed(3)}, the page says about 5.85`);
    ok(C.toFixed(2) === '3.60', `8*sqrt(2)/pi is ${C}`);
    said('6n − k − 2', 'plain square'); said('about 5.85', '600 random points');
    said('2√(2n)/π', 'half the density'); said('about 3.60√n for large n', 'k + 4 sits close to 3.60√n');
  }
  return fail === before;
}

// The plain-square Voronoi, as in research/why-are-basalt-columns-hexagonal/film/bounded.mjs (copied
// so this file still needs nothing but the page's own files): each cell is the square clipped by the
// bisector to every nearer point; its sides are its corners, frame corners included.
function clipPoly(poly, nx, ny, c) {
  const out = [];
  for (let i = 0; i < poly.length; i++) {
    const a = poly[i], b = poly[(i + 1) % poly.length];
    const fa = nx * a.x + ny * a.y - c, fb = nx * b.x + ny * b.y - c;
    if (fa <= 0) out.push(a);
    if ((fa < 0 && fb > 0) || (fa > 0 && fb < 0)) { const t = fa / (fa - fb); out.push({ x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) }); }
  }
  return out;
}
function voronoiSquare(P) {
  return P.map((p, i) => {
    let poly = [{ x: 0, y: 0 }, { x: 1, y: 0 }, { x: 1, y: 1 }, { x: 0, y: 1 }];
    const order = P.map((q, j) => [j, (q.x - p.x) ** 2 + (q.y - p.y) ** 2]).filter(([j]) => j !== i).sort((a, b) => a[1] - b[1]);
    for (const [j, d2] of order) {
      let r = 0;
      for (const v of poly) r = Math.max(r, (v.x - p.x) ** 2 + (v.y - p.y) ** 2);
      if (d2 > 4 * r + 1e-12) break; // farther than twice the cell's reach: cannot clip it
      const q = P[j], nx = q.x - p.x, ny = q.y - p.y;
      poly = clipPoly(poly, nx, ny, (nx * (q.x + p.x) + ny * (q.y + p.y)) / 2);
    }
    return poly.filter((a, k) => { const b = poly[(k + 1) % poly.length]; return Math.hypot(a.x - b.x, a.y - b.y) > 1e-10; });
  });
}
function framePoints(cells) {
  const edge = (v) => v.x < 1e-9 || v.y < 1e-9 || v.x > 1 - 1e-9 || v.y > 1 - 1e-9;
  const corner = (v) => (v.x < 1e-9 || v.x > 1 - 1e-9) && (v.y < 1e-9 || v.y > 1 - 1e-9);
  const seen = new Set();
  for (const c of cells) for (const v of c) if (edge(v) && !corner(v)) seen.add(`${v.x.toFixed(9)},${v.y.toFixed(9)}`);
  return seen.size;
}
function polyArea(poly) {
  let s = 0;
  for (let i = 0; i < poly.length; i++) { const a = poly[i], b = poly[(i + 1) % poly.length]; s += a.x * b.y - b.x * a.y; }
  return s / 2;
}

function summaryOf(s) {
  const n = s.counts ? Object.values(s.counts).reduce((a, b) => a + b, 0) : s.n;
  const share = s.counts ? Object.fromEntries(Object.entries(s.counts).map(([k, v]) => [k, v / n])) : Object.fromEntries(Object.entries(s.pct).map(([k, v]) => [k, v / 100]));
  let mean = 0, m2 = 0;
  for (const [k, f] of Object.entries(share)) mean += +k * f;
  for (const [k, f] of Object.entries(share)) m2 += f * (+k - mean) ** 2;
  return { n, mean, sigma: Math.sqrt(m2), hex: share[6] || 0, t: (6 - mean) / 2 };
}


const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const { SITES, RECOUNTS } = await import(pathToFileURL(join(dir, 'sites.mjs')).href);
const html = readFileSync(join(dir, 'index.html'), 'utf8');
await run(E, SITES, RECOUNTS, html, false);

if (MUTATE) {
  // Break the engine in ways that would make the page say something false; each must turn a check red.
  const { mkdtempSync, copyFileSync } = await import('node:fs');
  const { tmpdir } = await import('node:os');
  const src = readFileSync(join(dir, 'engine.mjs'), 'utf8');
  const MUT = [
    ['a T counted as a corner of the cell it runs straight through', 'if (Math.abs(turn(net, c, i)) > STRAIGHT) k++;', 'k++;'],
    ['the neighbour across a cut edge not told about the new vertex', 'r.splice(j + 1, 0, ids[k]);', 'void 0;'],
    ['a T given three corners in the count', 'return 3 * Y + 2 * T + 2 * frame + 4;', 'return 3 * Y + 3 * T + 2 * frame + 4;'],
    ['a pull that moves the junction along the line, not off it', 'P.x += nx * d; P.y += ny * d;', 'P.x += ny * d * 0; P.y += 0;'],
    ['the Voronoi cells ignoring the wrapped copies of neighbours', 'for (let wx = -1; wx <= 1; wx++) for (let wy = -1; wy <= 1; wy++) {\n            const qx', 'for (let wx = 0; wx <= 0; wx++) for (let wy = 0; wy <= 0; wy++) {\n            const qx'],
    ['discs that do not keep apart', 'if (dx * dx + dy * dy < d * d) { ok = false; break; }', 'if (false) { ok = false; break; }'],
    ["Calka's hexagon share misread", 'const CALKA = { 3: 0.011240, 4: 0.106838, 5: 0.25946, 6: 0.29473,', 'const CALKA = { 3: 0.011240, 4: 0.106838, 5: 0.25946, 6: 0.32473,'],
  ];
  let caught = 0;
  for (const [name, from, to] of MUT) {
    if (!src.includes(from)) { ok(false, `mutation "${name}" did not apply`); continue; }
    const d = mkdtempSync(join(tmpdir(), 'basalt-mut-'));
    writeFileSync(join(d, 'engine.mjs'), src.replace(from, to));
    const M = await import(pathToFileURL(join(d, 'engine.mjs')).href);
    const f0 = fail, p0 = pass;
    let red;
    try { red = !(await run(M, SITES, RECOUNTS, html, true)); } catch { red = true; }
    fail = f0; pass = p0;
    console.log(`  mutation: ${name}: ${red ? 'caught' : 'NOT CAUGHT'}`);
    if (red) caught++;
  }
  ok(caught === MUT.length, `${MUT.length - caught} mutation(s) not caught`);
  console.log(`mutations caught: ${caught}/${MUT.length}`);
}

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