#!/usr/bin/env node
// verify-stair-rise-and-run.mjs: checks /strata/stair-rise-and-run/ ("One Inch Up, Two Across").
//
//   node verify-stair-rise-and-run.mjs            # engine, rules, shapes, and every figure the page states
//   node verify-stair-rise-and-run.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
// ./stair-rise-and-run-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// What it checks:
//  A. the Paris foot, recomputed from the law of 10 December 1799 (1 m = 443.296 lignes, 144 lignes
//     to the foot), and Blondel's two feet in millimetres;
//  B. each authority's limits in the engine against the numbers its source states (written out
//     below, with the source's words, so a reader can compare them without the engine);
//  C. Blondel's table: every row makes 24 Paris inches;
//  D. each shaded shape against brute force: the polygon's area equals the area of a fine grid of
//     stairs that the rule itself passes, to within the grid's resolution;
//  E. every figure the prose quotes, recomputed here and found in the page's text, and the verdicts
//     the prose states (which rows pass which codes, which corners sit on the line).
// What it does NOT check: that the sources say what column B says they say. That was done by
// reading page images of the 1683 and 1685 books and the codes' texts; the words relied on are in
// assay/sources/stair-rise-and-run.json.

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

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'stair-rise-and-run';
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}`);

// B. What the sources say, in their own units. p = Paris inches (pouces), in = inches, mm = mm.
const STATED = {
  vitruvius: { u: 'p', rMin: 9, rMax: 10, gMin: 18, gMax: 24, words: 'neque crassiores dextante nec tenuiores dodrante ... nec minus quam sesquipedales nec plus quam bipedales' },
  alberti: { u: 'p', rMin: 9, rMax: 2, gMin: 18, gMax: 24, words: 'neque crassiores sextante neque tenuiores dodrante (Blondel: deux pouces ... neuf pouces)' },
  palladio: { u: 'p', rMin: 4, rMax: 6, gMin: 12, gMax: 18, words: "pas plus de six pouces ... pas moins de quatre pouces, leur largeur jamais moins d'un pied ny plus d'un pied & demy" },
  scamozzi: { u: 'p', rMin: 4, rMax: 5, gMin: 12, gMax: 14, words: "quatre ou cinq pouces ... un pied ou peu plus (14 is the page's drawing choice)" },
  savot: { u: 'p', rMax: 6, gMin: 12, words: "d'un pied pour le moins, & leur hauteur d'un demy pour le plus" },
  irc: { u: 'in', rMax: 7.75, gMin: 10, words: 'maximum riser height shall be 7 3/4 inches ... minimum tread depth shall be 10 inches' },
  ibc: { u: 'in', rMin: 4, rMax: 7, gMin: 11, words: '7 inches maximum and 4 inches minimum ... 11 inches minimum' },
  'uk-private': { u: 'mm', rMin: 150, rMax: 220, gMin: 220, gMax: 300, pitchMax: 42, sum: [550, 700], words: 'Private stair 150 220 220 300; maximum pitch 42°; 2R + G 550 to 700' },
  'uk-utility': { u: 'mm', rMin: 150, rMax: 190, gMin: 250, gMax: 400, sum: [550, 700], words: 'Utility stair 150 190 250 400' },
  'uk-general': { u: 'mm', rMin: 150, rMax: 170, gMin: 250, gMax: 400, sum: [550, 700], words: 'General access stair 150 170 250 400' },
};

const MUTANTS = [
  ['the Paris foot from the wrong ligne count', 'export const PIED_MM = (4500 / 13853) * 1000;', 'export const PIED_MM = (4500 / 13860) * 1000;'],
  ['Blondel counts the rise once', 'export const blondelSum = (R, G) => 2 * R + G;', 'export const blondelSum = (R, G) => R + G;'],
  ['IRC riser limit read as 7 1/2 inches', 'rMax: inch(7.75), gMin: inch(10),', 'rMax: inch(7.5), gMin: inch(10),'],
  ['UK pitch cap ignored', "if (a.pitchMax != null && pitchDeg(R, G) > a.pitchMax + 1e-9) f.push(`steeper than ${a.pitchMax}°`);", ''],
  ['polygon clip keeps the wrong side', 'if (fp >= 0) out.push(P);', 'if (fp <= 0) out.push(P);'],
];

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(/&amp;/g, '&').replace(/\s+/g, ' ');
  const says = (s, label) => ok(text.includes(s), `page says "${s}"${label ? ' (' + label + ')' : ''}`);
  const near = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
  const r1 = (x) => (Math.round(x * 10) / 10).toFixed(1);

  if (!quiet) console.log('A. units');
  const PIED = (144 / 443.296) * 1000;
  ok(near(E.PIED_MM, PIED, 1e-9), `Paris foot = 144/443.296 m = ${PIED.toFixed(4)} mm`);
  ok(near(E.POUCE_MM, PIED / 12, 1e-9), `Paris inch = ${(PIED / 12).toFixed(3)} mm`);
  ok(near(E.BLONDEL_PACE_MM, 2 * PIED, 1e-9), `two Paris feet = ${(2 * PIED).toFixed(2)} mm`);
  ok(near(E.INCH_MM, 25.4), 'inch = 25.4 mm');

  if (!quiet) console.log('B. each authority against what its source states');
  const unit = { p: PIED / 12, in: 25.4, mm: 1 };
  for (const [id, s] of Object.entries(STATED)) {
    const a = E.AUTHORITIES.find((x) => x.id === id);
    if (!a) { ok(false, `${id} present`); continue; }
    const k = unit[s.u];
    for (const f of ['rMin', 'rMax', 'gMin', 'gMax']) {
      const want = s[f] == null ? null : s[f] * k;
      ok(want == null ? a[f] == null : near(a[f], want, 1e-6), `${id} ${f} = ${s[f] ?? 'none'} ${s[f] == null ? '' : s.u}`);
    }
    ok((s.pitchMax ?? null) === (a.pitchMax ?? null), `${id} pitch cap = ${s.pitchMax ?? 'none'}`);
    ok(JSON.stringify(s.sum ?? null) === JSON.stringify(a.sum ?? null), `${id} 2R+G band = ${s.sum ? s.sum.join(' to ') : 'none'}`);
  }
  ok(E.AUTHORITIES.length === 11 && E.AUTHORITIES.filter((a) => a.line).length === 1, 'eleven entries, one of them (Blondel) a line');
  const books = new Set(E.AUTHORITIES.map((a) => a.name.replace(/^UK .*/, 'UK')));
  ok(books.size === 9, `nine authorities (the three UK categories are one document): ${[...books].join(', ')}`);

  if (!quiet) console.log("C. Blondel's table");
  ok(E.BLONDEL_TABLE.length === 9, 'nine rows, one to nine inches of rise');
  ok(E.BLONDEL_TABLE.every(([r, g], i) => r === i + 1 && 2 * r + g === 24), 'every row: 2 x rise + going = 24');
  ok(E.BLONDEL_TABLE.every(([r, g]) => near(E.offBlondel(r * E.POUCE_MM, g * E.POUCE_MM), 0, 1e-9)), 'every row sits on the engine line');

  if (!quiet) console.log('D. shapes against brute force');
  const h = 1; // mm grid
  for (const a of E.AUTHORITIES) {
    if (a.line) continue;
    let n = 0;
    for (let G = h / 2; G < E.WINDOW.gMax; G += h) for (let R = h / 2; R < E.WINDOW.rMax; R += h) if (E.passes(a, R, G)) n++;
    const grid = n * h * h, poly = E.polygonArea(E.regionPolygon(a));
    const per = Math.max(50, 2 * (a.rMax ?? 300) + 2 * (a.gMax ?? 700)); // perimeter bound for the grid's edge error
    ok(Math.abs(grid - poly) <= per * h, `${a.id}: polygon ${poly.toFixed(0)} mm² vs grid ${grid.toFixed(0)} mm²`);
  }
  ok(E.regionPolygon(E.AUTHORITIES.find((a) => a.id === 'alberti')).length === 0, "Alberti's shape is empty");

  if (!quiet) console.log('E. the figures and verdicts in the prose');
  const find = (id) => E.AUTHORITIES.find((a) => a.id === id);
  says(`${(PIED / 12).toFixed(2)} mm`, 'Paris inch');
  says(`${r1(2 * PIED)} mm`, 'two Paris feet');
  says(`${r1(PIED)} mm rung`, 'the ladder, one foot');
  says('443.296', 'the 1799 definition');
  says('4500/13853', 'the foot as a fraction of a metre');
  // Figures bound to their own sentences, so a second copy elsewhere cannot vouch for an edited one.
  says(`Blondel's two feet are ${r1(2 * PIED)} mm`, 'the pace sentence');
  says(`a ${r1(2 * PIED)} mm pace`, 'the plane caption');
  says('go fall between 550 and 700 millimetres'.slice(3), 'the dek (UK band)');
  ok(JSON.stringify(find('uk-private').sum) === '[550,700]', 'the UK band the dek states is the engine band');
  says('capped at a pitch of 42°', 'UK pitch cap'); ok(find('uk-private').pitchMax === 42, '...and the engine cap is 42');
  says('a riser of at most 7¾ inches on a tread of at least 10', 'IRC limits'); ok(near(find('irc').rMax, 7.75 * 25.4) && near(find('irc').gMin, 254), '...as the engine has them');
  says('stops at 7 on 11', 'IBC limits');
  says('Twice six plus twelve is twenty-four'); ok(2 * 6 + 12 === 24, 'twice six plus twelve');
  says('was 27.07 mm: the law of 10 December 1799', 'the inch sentence');
  ok(near(4500 / 13853, 144 / 443.296, 1e-15), '4500/13853 = 144/443.296');
  const irc = E.steepestCorner(find('irc')), ibc = E.steepestCorner(find('ibc'));
  says(`${r1(irc.sum)} mm`, 'IRC corner 2R+G'); says(`${r1(-irc.off)} mm short`, 'IRC corner vs two feet');
  ok(near(2 * 7.75 + 10, 25.5), 'IRC corner = 25.5 inches'); says('25.5 inches');
  says(`${r1(ibc.sum)} mm`, 'IBC corner'); says(`${r1(-ibc.off)} mm short`, 'IBC corner vs two feet');
  const cap = E.blondelAtPitch(42);
  says(`rise of ${r1(cap.R)} mm on a going of ${r1(cap.G)} mm`, '42° cap meets the line');
  const seg = E.blondelSegment(find('uk-private'));
  ok(!!seg && near(seg.rTo, cap.R, 0.02), 'the private box admits the line up to the 42° cap');
  if (seg) says(`from a rise of ${r1(seg.rFrom)} mm`, 'where the private box first admits the line');
  ok(!!seg && near(seg.gFrom, 300, 0.05), '...which is where the going reaches its 300 mm maximum');
  says('36 to 44 inches'); ok(2 * 9 + 18 === 36 && 2 * 10 + 24 === 44, 'Vitruvius: 2R+G from 36 to 44 Paris inches');
  ok(36 / 24 === 1.5 && 44 / 24 > 1.5, "Vitruvius's box is half as much again as the pace, or more");
  says('20 to 22 inches'); ok(2 * 4 + 12 === 20 && 2 * 5 + 12 === 22, 'Scamozzi on a one-foot tread: 20 to 22');
  for (const id of ['palladio', 'savot']) ok(near(E.offBlondel(6 * E.POUCE_MM, 12 * E.POUCE_MM), 0, 1e-9) && E.passes(find(id), 6 * E.POUCE_MM, 12 * E.POUCE_MM) && !E.passes(find(id), 6 * E.POUCE_MM + 0.01, 12 * E.POUCE_MM - 0.01), `${id}: six on twelve is allowed, is its steepest corner, and is on the line`);
  ok(E.passes(find('palladio'), 4 * E.POUCE_MM, 16 * E.POUCE_MM), "the line runs through Palladio's box to four on sixteen");
  says("exactly on Blondel's line");
  const modern = E.AUTHORITIES.filter((a) => a.era === 'new');
  const passing = (r, g) => modern.filter((a) => E.passes(a, r * E.POUCE_MM, g * E.POUCE_MM)).map((a) => a.id).join(',');
  ok(passing(8, 8) === '' && passing(9, 6) === '', 'rows eight on eight and nine on six pass no modern code');
  ok(r1(E.pitchDeg(1, 1)) === '45.0' && Math.round(E.pitchDeg(9, 6)) === 56, 'their pitches: 45° and 56°');
  says('a 45° stair'); says('and nine on six, 56°');
  ok(passing(7, 10) === 'irc,uk-private,uk-utility', `row seven on ten passes exactly: ${passing(7, 10)}`);
  says(`${r1(7 * E.POUCE_MM)} mm on ${r1(10 * E.POUCE_MM)} mm`, 'row seven on ten in mm');
  ok(E.BLONDEL_PACE_MM > 550 && E.BLONDEL_PACE_MM < 700, "two Paris feet lie inside England's 550 to 700");
  return { pass, fail };
}

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

if (MUTATE) {
  console.log('\nmutants (each must turn at least one check red):');
  const tmp = mkdtempSync(join(tmpdir(), 'stairs-'));
  let i = 0;
  for (const [name, from, to] of MUTANTS) {
    if (!engineSrc.includes(from)) { console.log(`  FAIL mutant "${name}": its target text is not in the engine`); bad = true; continue; }
    const f = join(tmp, `engine-m${i++}.mjs`);
    writeFileSync(f, engineSrc.replace(from, to));
    let r;
    try { r = await checks(pathToFileURL(f).href, html, true); } catch (e) { r = { fail: 1, crashed: e.message }; }
    console.log(`  ${r.fail > 0 ? 'ok  ' : 'FAIL'} ${name}: ${r.fail} check(s) red`);
    if (r.fail === 0) bad = true;
  }
}
process.exit(bad ? 1 : 0);
