#!/usr/bin/env node
// verify-keplers-wine-barrel.mjs: checks /strata/keplers-wine-barrel/ ("Imperceptible at First").
//
//   node verify-keplers-wine-barrel.mjs            # the geometry, Kepler's printed figures, the page's prose
//   node verify-keplers-wine-barrel.mjs --mutate   # also break the engine on purpose; the 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
// ./keplers-wine-barrel-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// What it does NOT check: the quotations. Those were read by hand against page images of the 1615
// Latin print and the 1616 German print; the page says where.

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

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'keplers-wine-barrel';
const MUTATE = process.argv.includes('--mutate');
let dir = join(here, 'public/strata', slug);
if (!existsSync(join(dir, 'engine.mjs'))) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  for (const f of ['engine.mjs', 'index.html']) {
    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 engineSrc = readFileSync(join(dir, 'engine.mjs'), 'utf8');
const html = readFileSync(join(dir, 'index.html'), 'utf8');
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(/\s+/g, ' ');
// A figure is only "stated" if it sits in the same sentence as what it is a figure of.
const sentences = text.split(/(?<=[.!?;])\s+(?=[A-Z0-9“(])/);
const stated = (needles) => sentences.some((s) => needles.every((n) => s.includes(n)));

// ---- an independent model, written without looking at the engine's code paths ----
// Half-cask of half-length a and diameter b with a^2 + b^2 = rod^2; content of the whole cask
// is 2 * (pi/4) b^2 a. Search the best shape numerically instead of using the closed form.
const wholeCask = (a, rod = 1) => Math.PI / 2 * (rod * rod - a * a) * a;
function bestByGolden(rod = 1) {
  let lo = 0, hi = rod; const g = (Math.sqrt(5) - 1) / 2;
  for (let i = 0; i < 300; i++) {
    const m1 = hi - g * (hi - lo), m2 = lo + g * (hi - lo);
    if (wholeCask(m1, rod) < wholeCask(m2, rod)) lo = m1; else hi = m2;
  }
  const a = (lo + hi) / 2, b = Math.sqrt(rod * rod - a * a);
  return { a, b, k: 2 * a / b, V: wholeCask(a, rod) };
}
const BEST = bestByGolden();
const shareAt = (k) => { const b = 1 / Math.sqrt(1 + k * k / 4); return wholeCask(k * b / 2) / BEST.V; };

async function suite(E, { quiet = false } = {}) {
  let pass = 0, fail = 0;
  const check = (name, ok, detail = '') => {
    if (ok) pass++; else fail++;
    if (!quiet) console.log(`${ok ? 'ok  ' : 'FAIL'} ${name}${detail ? '  (' + detail + ')' : ''}`);
    return ok;
  };
  const near = (a, b, tol) => Math.abs(a - b) <= tol;

  // ---------------------------------------------------------------- 1. the geometry
  check('the best shape is length = sqrt2 x diameter (golden-section search vs the engine)',
    near(BEST.k, Math.SQRT2, 1e-6) && near(E.BEST_K, BEST.k, 1e-6), `search ${BEST.k.toFixed(6)}, engine ${E.BEST_K.toFixed(6)}`);
  check('the best content is pi/(3 sqrt3) rod^3 = 0.6046', near(E.vmaxCoef, BEST.V, 1e-9) && near(BEST.V, 0.6046, 5e-5), BEST.V.toFixed(6));
  let worst = 0;
  for (let k = 0.3; k < 6; k += 0.01) worst = Math.max(worst, Math.abs(E.fraction(k) - shareAt(k)));
  check('the engine\'s share-of-best matches the independent model at 570 shapes', worst < 1e-9, `worst ${worst.toExponential(2)}`);
  let rodWorst = 0;
  for (let k = 0.3; k < 6; k += 0.37) {
    const c = E.cylinderAtRod(1, k);
    // the engine's own rod function, and the geometry (bung at mid-length, down one diameter), must both say 1
    rodWorst = Math.max(rodWorst, Math.abs(E.cylinder.rod(c.L, c.D) - 1), Math.abs(Math.hypot(c.L / 2, c.D) - 1));
  }
  check('every cask the engine builds on the arc has rod length 1, by its own rod() and by the geometry', rodWorst < 1e-12, rodWorst.toExponential(2));
  const [lo, hi] = E.band(0.01);
  check('the served HTML\'s static 0.6046 matches the engine', html.includes('<span id="vmax-live">' + E.vmaxCoef.toFixed(4) + '</span>'));
  check('the exact miss from 20/sqrt3 to 12 is 0.453', (12 - E.H_AUSTRIA).toFixed(3) === '0.453');
  check('the 1% band is 1.25 to 1.60', lo.toFixed(2) === '1.25' && hi.toFixed(2) === '1.60' && near(shareAt(lo), 0.99, 1e-6) && near(shareAt(hi), 0.99, 1e-6), `${lo.toFixed(4)} to ${hi.toFixed(4)}`);
  check('as long as wide holds 93%; twice as long, 92%; the coopers\' 1.5 holds 99.8%',
    Math.round(100 * E.fraction(1)) === 93 && Math.round(100 * E.fraction(2)) === 92 && (100 * E.fraction(1.5)).toFixed(1) === '99.8',
    `${(100 * E.fraction(1)).toFixed(2)}, ${(100 * E.fraction(2)).toFixed(2)}, ${(100 * E.fraction(1.5)).toFixed(2)}`);
  const l10 = 1 - shareAt(Math.SQRT2 * 1.1), l20 = 1 - shareAt(Math.SQRT2 * 1.2);
  check('10% longer loses 0.6%, 20% longer 2.3%; the square rule says 0.6% and 2.2%',
    (100 * l10).toFixed(1) === '0.6' && (100 * l20).toFixed(1) === '2.3' &&
    (100 * (1 - E.fractionQuadratic(Math.SQRT2 * 1.1))).toFixed(1) === '0.6' && (100 * (1 - E.fractionQuadratic(Math.SQRT2 * 1.2))).toFixed(1) === '2.2',
    `${(100 * l10).toFixed(3)}%, ${(100 * l20).toFixed(3)}%`);
  // the curvature: finite-difference second derivative of ln(share) in u = ln(k/sqrt2)
  const h = 1e-4, f = (u) => Math.log(shareAt(Math.SQRT2 * Math.exp(u)));
  const d2 = (f(h) - 2 * f(0) + f(-h)) / (h * h);
  check('near the top, share = exp(-(2/3) u^2): curvature -4/3 by finite difference', near(d2, -4 / 3, 1e-4) && near(E.CURVATURE, 2 / 3, 1e-12), d2.toFixed(6));
  check('a 1% misreading of the rod is a 3% error in the reading', (100 * E.readingError(0.01)).toFixed(1) === '3.0');

  // ---------------------------------------------------------------- 2. Kepler's own figures
  // Printed in Messekunst Archimedis (1616), ch. 76, pp. 64-65. Transcribed by hand from the print.
  const PRINTED = [[11, 3069], [20 / Math.sqrt(3), 3080], [12, 3072], [14, 2856], [Math.sqrt(200), 2828], [15, 2625]];
  const mine = (hh) => (400 - hh * hh) * hh;
  let rows = 0;
  for (const [hh, p] of PRINTED) if (Math.round(mine(hh)) === p || (p === 3080 && Math.round(mine(hh)) === 3079)) rows++;
  check('all six of Kepler\'s printed figures recompute from (400 - h^2) h (3080 is 3079.2 rounded)', rows === 6, `${rows}/6`);
  const eRows = E.KEPLER_ROWS.map((r) => [r.h, r.printed]);
  check('the engine carries the same six rows', eRows.length === 6 && eRows.every(([hh, p], i) => near(hh, PRINTED[i][0], 1e-9) && p === PRINTED[i][1] && near(E.leib(hh), mine(hh), 1e-9)));
  check('his losses: one in 385, one in 280, not quite 12, one in 101, 203 and the 14th',
    E.oneIn(3080, 3072) === 385 && E.oneIn(3080, 3069) === 280 && E.oneIn(3080, 2828) < 12.5 && E.oneIn(3080, 2828) > 12 &&
    E.oneIn(2828, 2856) === 101 && 2828 - 2625 === 203 && Math.ceil(E.oneIn(2828, 2625)) === 14);
  check('against the unrounded best, 3072 is one in 428', Math.round(E.oneIn(mine(20 / Math.sqrt(3)), 3072)) === 428);
  const a5 = Math.abs(E.coopersMiss(E.H_AUSTRIA, 0.5)), r5 = Math.abs(E.coopersMiss(E.H_RHINE, 0.5));
  const a5m = Math.abs(E.coopersMiss(E.H_AUSTRIA, -0.5)), r5m = Math.abs(E.coopersMiss(E.H_RHINE, -0.5));
  check('a miss of half a part costs the Rhenish cask more than ten times the Austrian (both directions)',
    r5 / a5 > 10 && r5m / a5m > 10, `${(r5 / a5).toFixed(1)}x, ${(r5m / a5m).toFixed(1)}x`);
  check('the Austrian and Rhenish aims are 20/sqrt3 and 20/sqrt2', near(E.H_AUSTRIA, 20 / Math.sqrt(3), 1e-12) && near(E.H_RHINE, 20 / Math.SQRT2, 1e-12));

  // ---------------------------------------------------------------- 3. the Linz rod (ch. 93)
  // 1 Schuh = 12 Zoll x 19 puncten = 228; 100 puncten of rod = 1 Achtering, so content = (reading/100)^3 Achtering.
  const ach = (schuh) => Math.pow(schuh * 228 / 100, 3);
  check('the Linz rod: 1.5 Schuh -> 40 Achtering (a small Eimer), 3 -> 8 Eimer, 6 -> 64 Eimer',
    Math.round(ach(1.5)) === 40 && Math.round(ach(3) / 40) === 8 && Math.round(ach(6) / 40) === 64, `${ach(1.5).toFixed(3)}`);
  check('its constant is 0.6141 rod^3, 1.6% above the best cylinder', near(E.LINZ_ROD_COEF, 0.61411, 1e-9) && (100 * (E.LINZ_ROD_COEF / BEST.V - 1)).toFixed(1) === '1.6');

  // ---------------------------------------------------------------- 4. the prose, each figure in its own sentence
  const P = [
    ['as long as it is wide holds 93%', ['as long as it is wide holds', '93%']],
    ['twice as long as it is wide, 92%', ['twice as long as it is wide', '92%']],
    ['the 1% band', ['1.25 to 1.60', 'within 1%']],
    ['the coopers\' rule at 99.8%', ['at 1.5', '99.8%']],
    ['sqrt2 ~ 1.41', ['√2 ≈ 1.41']],
    ['10% longer loses 0.6%', ['10% longer', 'loses 0.6%']],
    ['20% longer, 2.3%; the square rule 0.6% and 2.2%', ['20% longer, 2.3%', 'estimates 0.6% and 2.2%']],
    ['more than ten times', ['half a part', 'more than ten times']],
    ['misread by 1% gives about 3%', ['misreads the rod itself by 1%', 'about 3%']],
    ['one part in 385', ['3072', '3080', 'one part in 385']],
    ['one in 428 unrounded', ['3079.2', 'one in 428']],
    ['one in 280', ['One part too short', 'one in 280']],
    ['the Rhenish loss, one in about 12', ['Rhenish cask', 'one in about 12']],
    ['one part in 101', ['14 instead of 14.14', 'one part in 101']],
    ['203 and the 14th', ['lost 203', '14th Eimer']],
    ['the Linz constants', ['0.6141', 'the cube of the reading']],
    ['0.6046 and 1.6%', ['0.6046', '1.6%']],
    ['40 Achtering, 8 Eimer, 64', ['40 Achtering', '8 Eimer', '64']],
    ['the check panel restates his losses', ['one in 385, one in 280, one in about 12, one in 101, the 14th']],
    ['the check panel: all six agree', ['all six agree to the unit']],
    ['the exact miss to 12 is 0.453', ['from 11.547 to 12 is 0.453']],
    ['the instrument reading at +0.45', ['reading at +0.45']],
    ['the 2625 note', ['reads the last one as 1625', 'shows 2625', 'difference of 203']],
  ];
  for (const [name, needles] of P) check(`prose: ${name}`, stated(needles));
  return { pass, fail };
}

const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const { pass, fail } = await suite(E);
console.log(`\n${pass} passed, ${fail} failed`);
let bad = fail > 0;

if (MUTATE) {
  const mutants = [
    ['best shape moved to 1.5', [/export const BEST_K = Math\.SQRT2;/, 'export const BEST_K = 1.5;']],
    ['the rod spans the whole length, not half', [/Math\.hypot\(L \/ 2, D\)/, 'Math.hypot(L, D)']],
    ['cylinderAtRod forgets the half', [/Math\.sqrt\(1 \+ \(k \* k\) \/ 4\)/, 'Math.sqrt(1 + k * k)']],
    ["Kepler's 3072 misread as 3027", [/printed: 3072/, 'printed: 3027']],
    ['Rhenish aim taken as h = 15', [/export const H_RHINE = KROD \/ Math\.SQRT2;/, 'export const H_RHINE = 15;']],
    ['the rod error squared instead of cubed', [/Math\.pow\(1 \+ e, 3\) - 1/, 'Math.pow(1 + e, 2) - 1']],
    ['the Linz Achtering off by one digit', [/614110 \/ 1e6/, '641110 / 1e6']],
  ];
  console.log('\n--mutate: each planted fault must turn at least one check red');
  const mdir = mkdtempSync(join(tmpdir(), 'kwb-mutants-')); // never inside the served folder
  let k = 0;
  for (const [name, [re, rep]] of mutants) {
    if (!re.test(engineSrc)) { console.log(`FAIL mutant "${name}": pattern not found in engine`); bad = true; continue; }
    const f = join(mdir, `engine-${k++}.mjs`);
    writeFileSync(f, engineSrc.replace(re, rep));
    const M = await import(pathToFileURL(f).href);
    const r = await suite(M, { quiet: true });
    const caught = r.fail > 0;
    console.log(`${caught ? 'ok  ' : 'FAIL'} mutant caught: ${name}  (${r.fail} checks red)`);
    if (!caught) bad = true;
  }
  rmSync(mdir, { recursive: true, force: true });
}
process.exit(bad ? 1 : 0);
