#!/usr/bin/env node
// verify-why-are-bricks-that-size.mjs: checks /strata/why-are-bricks-that-size/ ("Two Headers and a Joint").
//
//   node verify-why-are-bricks-that-size.mjs            # formats, sums, walls, and every figure the page states
//   node verify-why-are-bricks-that-size.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-are-bricks-that-size-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// What it checks:
//  A. each brick in the engine against the size and joint its source states (written out below,
//     in the source's own units, with the source's words, so a reader can compare without the engine);
//  B. the rule L = 2W + j across the standards: which leave exactly their stated joint, and which do not;
//  C. the walls, laid brick by brick: straight joints, laps and the joints a mason would need;
//  D. heights and coursing;
//  E. every figure the prose quotes, recomputed here and found in its own sentence on the page.
// What it does NOT check: that the sources say what column A says they say. The words relied on,
// with the URL and the date each was fetched, are in assay/sources/why-are-bricks-that-size.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 = 'why-are-bricks-that-size';
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}`);

// A. What the sources say. u: 'mm' or 'in'. j: the joint the source names (null: it names none).
const STATED = {
  uk: { u: 'mm', L: 215, W: 102.5, H: 65, j: 10, words: 'BDA: work size 215 x 102.5 x 65; nominal 10mm mortar joints; co-ordinating size 225 x 112.5 x 75mm' },
  us: { u: 'in', L: 7.625, W: 3.625, H: 2.25, j: 0.375, words: 'BIA TN10: a modular brick would be specified as 3 5/8 in. x 2 1/4 in. x 7 5/8 in.; joint 3/8' },
  'de-nf': { u: 'mm', L: 240, W: 115, H: 71, j: 10, words: 'BauNetz: Normalformat (NF): 240 mm x 115 mm x 71 mm; Ziegel-Zentrum: Stossfugen 10 mm, Lagerfugen 12 mm' },
  'de-df': { u: 'mm', L: 240, W: 115, H: 52, j: 10, words: 'Duennformat (DF): 240 mm x 115 mm x 52 mm' },
  'de-2df': { u: 'mm', L: 240, W: 115, H: 113, j: 10, words: '1,5 NF = 2 DF: 240 mm x 115 mm x 113 mm' },
  cn: { u: 'mm', L: 240, W: 115, H: 53, j: 10, words: 'GB/T 5101: 长240mm、宽115mm、高53mm; GB 50203 5.3.2: 宜为10mm' },
  dk: { u: 'mm', L: 228, W: 108, H: 54, j: 12, words: "Mur & Tag: 228x108x54 mm ('Dansk normalformat'); Tegelmaester: 12 mm joints" },
  se: { u: 'mm', L: 250, W: 120, H: 62, j: null, words: 'Randers Tegl: svenskt normalformat 250 x 120 x 62 mm' },
  ru: { u: 'mm', L: 250, W: 120, H: 65, j: 10, words: 'GOST 530-2012 Table 2: 250 120 65 1 NF; SP 70.13330.2012 9.2.4: vertical joints 10 mm' },
  'ru-14': { u: 'mm', L: 250, W: 120, H: 88, j: 10, words: 'GOST 530-2012 Table 2: 250 120 88 1,4 NF' },
  nl: { u: 'mm', L: 210, W: 100, H: 50, j: 10, words: 'KNB: Waalformaat 210 x 100 x 50; Wienerberger: 10 mm stootvoeg' },
  'nl-dik': { u: 'mm', L: 210, W: 100, H: 65, j: 10, words: 'KNB: Waaldikformaat 210 x 100 x 65' },
  jp: { u: 'mm', L: 210, W: 100, H: 60, j: null, words: 'JIS R 1250:2011 Table 4: 普通れんが 210 100 60' },
  'in-mod': { u: 'mm', L: 190, W: 90, H: 90, j: 10, words: 'IS 1077: 190 x 90 x 90 mm; IS 2212: allowance of 1 cm for mortar joint' },
  'in-non': { u: 'mm', L: 230, W: 110, H: 70, j: null, words: 'IS 1077 6.1.2: 230 x 110 x 70 mm' },
  au: { u: 'mm', L: 230, W: 110, H: 76, j: 10, words: 'Midland: MANUFACTURING SIZE: 230 X 110 X 76mm; Brickery: Mortar joints should be 10mm +/-2mm' },
  za: { u: 'mm', L: 222, W: 106, H: 73, j: 12, words: 'Clay Brick Association: 222mm x 106mm x 73mm, and the use of 12mm mortar joints is recommended' },
  'ru-07': { u: 'mm', L: 250, W: 85, H: 65, j: 10, words: 'GOST 530-2012 Table 2: 250 85 65 0,7 НФ; SP 70: vertical 10 mm' },
  'ru-13': { u: 'mm', L: 288, W: 138, H: 65, j: 10, words: 'GOST 530-2012 Table 2: 288 138 65 1,3 НФ' },
  'nl-limburg': { u: 'mm', L: 240, W: 120, H: 65, j: null, words: 'KNB: Limburgse steen 240 x 120 x 65' },
  'nl-groningen': { u: 'mm', L: 240, W: 120, H: 60, j: null, words: 'KNB: Groninger steen 240 x 120 x 60' },
  'nl-moef': { u: 'mm', L: 215, W: 100, H: 65, j: null, words: 'KNB: Moef 215 x 100 x 65' },
  'nl-brabant': { u: 'mm', L: 180, W: 88, H: 53, j: null, words: 'KNB: Brabantse steen 180 x 88 x 53' },
  'us-norman': { u: 'in', L: 11.625, W: 3.625, H: 2.25, j: 0.375, words: 'BIA TN10 Table 1: Norman ... 3 5/8 ... 2 1/4 ... 11 5/8' },
  e1571: { u: 'in', L: 9, W: 4.25, H: 2.25, j: null, words: 'nine inches, and in breadth four inches and one quarter, and two inches and one quarter in thickness' },
  e1625: { u: 'in', L: 9, W: 4.375, H: 2.25, j: null, words: 'nyne ynches, in bredth fower inches one quarter and half a quarter of an ynch ... two ynches and one quarter' },
  e1725: { u: 'in', L: 9, W: 4.25, H: 2.5, j: null, words: 'not less than nine Inches long, and two Inches and an Half thick, and four inches and a Quarter wide' },
  e1777: { u: 'in', L: 8.5, W: 4, H: 2.5, j: null, words: 'not less than eight Inches and an Half long ... two Inches and an Half thick ... four Inches wide' },
  eb1911: { u: 'in', L: 9, W: 4.5, H: 3, j: null, words: 'viz. 9 x 4 1/2 x 3 in.' },
  harappa: { u: 'mm', L: 280, W: 140, H: 70, j: null, words: 'Kak: 1:2:4 with the dominating size being 7 x 14 x 28 cm' },
  eridu: { u: 'mm', L: 260, W: 130, H: 70, j: null, words: 'Hnaihen: (26x13x7 cm)' },
  'wp-cn': { u: 'mm', L: 240, W: 155, H: 53, j: null, words: '|{{CHN}} || {{convert|240|x|155|x|53|mm|in|disp=table}}' },
};
const NHBC = [6, 15]; // 'not less than 6mm nor more than 15mm'

const MUTANTS = [
  ['the rule forgets the joint', 'return L - 2 * W - j;', 'return L - 2 * W;'],
  ['the header perpend a mason needs, halved wrong', 'return (L + j) / 2 - W;', 'return (L + j) / 2 - W / 2;'],
  ['the queen closer cut to a full half brick', 'const q = (W - j) / 2;', 'const q = W / 2;'],
  ['the stretcher-bond corner shows no return end', "pieces.push({ x0: 0, x1: W, kind: 'E' });\n      run(W + j, L + j, L, 'S', len, pieces);", "run(0, L + j, L, 'S', len, pieces);"],
  ['the Danish brick read as 58 high and 105 wide', "L: 228, W: 108, H: 54,", "L: 228, W: 105, H: 58,"],
  ['NHBC range read as 5 to 15', 'export const JMIN = 6, JMAX = 15;', 'export const JMIN = 5, JMAX = 15;'],
];

async function checks(engineUrl, html, quiet = false) {
  // (html is the page source: the meta description is checked in it, the prose in its text)
  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(/&middot;/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 f = (id) => E.FORMATS.find((x) => x.id === id);

  if (!quiet) console.log('A. each brick against what its source states');
  for (const [id, s] of Object.entries(STATED)) {
    const b = f(id);
    if (!b) { ok(false, `${id} present`); continue; }
    const k = s.u === 'in' ? 25.4 : 1;
    ok(near(b.L, s.L * k, 1e-9) && near(b.W, s.W * k, 1e-9) && near(b.H, s.H * k, 1e-9), `${id}: ${s.L} x ${s.W} x ${s.H} ${s.u}`);
    ok(s.j == null ? b.joint == null : near(b.joint, s.j * k, 1e-9), `${id}: joint ${s.j == null ? 'not stated' : s.j + ' ' + s.u}`);
  }
  ok(E.FORMATS.length === Object.keys(STATED).length, `no brick in the engine without a stated source here (${E.FORMATS.length})`);
  ok(E.JMIN === NHBC[0] && E.JMAX === NHBC[1], 'joint range 6 to 15 mm (NHBC 6.1)');

  if (!quiet) console.log('B. the rule across the standards');
  const S = E.STANDARDS;
  const countries = new Set(S.map((b) => b.id.split('-')[0]));
  ok(S.length === 17, `seventeen principal two-to-one formats (${S.length})`);
  ok(countries.size === 12, `from twelve countries (${[...countries].join(', ')})`);
  const exact = S.filter((b) => b.joint != null && near(E.impliedJoint(b.L, b.W), b.joint, 1e-9)).map((b) => b.id);
  const noJoint = S.filter((b) => b.joint == null);
  const off = S.filter((b) => b.joint != null && !near(E.impliedJoint(b.L, b.W), b.joint, 1e-9));
  ok(off.length === 1 && off[0].id === 'za' && near(E.residual(off[0].L, off[0].W, off[0].joint), -2), `only South Africa misses its stated joint, by 2 mm`);
  ok(exact.length === 13 && S.filter((b) => b.joint != null).length === 14, `fourteen name a joint, thirteen leave exactly it (${exact.length})`);
  ok(noJoint.map((b) => b.id).join() === 'se,jp,in-non' && noJoint.every((b) => near(E.impliedJoint(b.L, b.W), 10)), "Sweden, Japan and India's non-modular name no joint and leave exactly 10");
  const by = (j) => S.filter((b) => b.joint != null && near(b.joint, j) && near(E.impliedJoint(b.L, b.W), j)).map((b) => b.id.split('-')[0]);
  ok(JSON.stringify([...new Set(by(10))].sort()) === JSON.stringify(['au', 'cn', 'de', 'in', 'nl', 'ru', 'uk']), `10 mm stated and left: ${[...new Set(by(10))].join(', ')}`);
  ok(by(12).join() === 'dk', '12 mm stated and left: Denmark');
  ok(near(E.impliedJoint(f('us').L, f('us').W), 0.375 * 25.4) && near(0.375 * 25.4, 9.525), 'US: 7 5/8 - 2 x 3 5/8 = 3/8 in = 9.525 mm');
  ok(S.every((b) => E.absorbable(b.L, b.W, b.joint ?? 10, E.JMIN, E.JMAX).ok), 'every standard bonds within 6 to 15 mm joints');
  ok(near(2 * 102.5 + 10, 215), '2 x 102.5 + 10 = 215');
  const nm = f('us-norman');
  ok(near(E.residualN(nm.L, nm.W, nm.joint, 3), 0) && near(3 * 3.625 + 2 * 0.375, 11.625), 'Norman: 3 x 3 5/8 + 2 x 3/8 = 11 5/8');
  const band = E.bondBand(100, 6, 15);
  ok(near(band[0], 197) && near(band[1], 224), 'band at W = 100 runs from 2W - 3 to 2W + 24');

  if (!quiet) console.log('C. the walls, brick by brick');
  const wall = (L, W, j, jh = j) => E.laps(E.englishBond({ L, W, H: 65, j, jh, len: 4000, courses: 8 }));
  const uk = wall(215, 102.5, 10);
  ok(!E.firstBelow(uk, 10) && near(Math.min(...uk.map((l) => l.lap)), 56.25, 1e-9), 'UK brick: no straight joint in 4 m; smallest lap a quarter pitch, 56.25 mm');
  const long5 = wall(220, 102.5, 10), fs = E.firstBelow(long5, 10);
  ok(!!fs && fs.x > 2200 && fs.x < 2400, `220 mm brick: first straight joint at ${fs && (fs.x / 1000).toFixed(3)} m`);
  ok(!!fs && (fs.x / 1000).toFixed(1) === '2.3', '...which is about 2.3 m');
  // an independent count: the header perpends start a quarter pitch (W + j)/2 from the stretcher perpends
  // and close by the residual per stretcher; the gap falls below one joint after ((W + j)/2 - j)/5 stretchers.
  const n = Math.ceil(((102.5 + 10) / 2 - 10) / 5);
  ok(Math.abs(fs.x - n * 230) <= 230, `...within one stretcher of the closed form (${n} stretchers, ${(n * 230 / 1000).toFixed(2)} m)`);
  const jh = E.headerPerpToAbsorb(220, 102.5, 10);
  ok(near(jh, 12.5) && !E.firstBelow(wall(220, 102.5, 10, jh), 10), 'header perpends at 12.5 mm take up the 5 mm');
  const wp = f('wp-cn');
  ok(near(2 * wp.W + 10, 320) && near(E.headerPerpToAbsorb(wp.L, wp.W, 10), -30), 'Wikipedia China row: two headers and a joint = 320; header perpends would be -30 mm');
  const fw = E.firstBelow(wall(wp.L, wp.W, 10), 10);
  ok(!!fw && (fw.x / 1000).toFixed(2) === '0.24', `...first straight joint at ${fw && (fw.x / 1000).toFixed(2)} m`);
  ok(near(E.impliedJoint(wp.L, wp.W), -70) && near(E.residual(wp.L, wp.W, 10), -80), '...70 mm below L = 2W, 80 below the gold line');
  ok(!E.STANDARDS.some((b) => !E.absorbable(b.L, b.W, b.joint ?? 10, 6, 15).ok) && !E.absorbable(wp.L, wp.W, 10, 6, 15).ok, 'every principal format is on the band; the Wikipedia row is not');
  ok(E.FORMATS.filter((b) => b.id !== 'wp-cn').every((b) => E.impliedJoint(b.L, b.W) > E.impliedJoint(wp.L, wp.W)), 'no other brick on the page sits lower than the Wikipedia row');
  const oth = (id) => E.impliedJoint(f(id).L, f(id).W);
  ok(near(oth('ru-07'), 80) && near(oth('ru-13'), 12) && near(oth('nl-limburg'), 0) && near(oth('nl-groningen'), 0) && near(oth('nl-moef'), 15) && near(oth('nl-brabant'), 4), 'other formats: L - 2W = 80, 12, 0, 0, 15, 4');
  says('a brick 250 by 85 (two widths are 80 mm short of a length)'); says('one of 288 by 138 (12 mm over, against a 10 mm vertical joint)');
  says('the Limburg and Groningen bricks are 240 by 120, exactly two widths long, the Moef is 215 by 100, leaving 15, and the Brabant 180 by 88, leaving 4');
  // stretcher bond: perpends of the corner course sit L - W from the course below; half bond wants (L + j)/2
  for (const b of S) {
    const ls = E.laps(E.stretcherBond({ L: b.L, W: b.W, H: b.H, j: b.joint ?? 10, len: 3000, courses: 4 }));
    const want = (b.L + (b.joint ?? 10)) / 2;
    const worst = Math.max(...ls.map((l) => Math.abs(l.lap - want)));
    ok(worst <= Math.abs(E.residual(b.L, b.W, b.joint ?? 10)) + 1e-9, `stretcher bond, ${b.id}: every lap within ${Math.abs(E.residual(b.L, b.W, b.joint ?? 10))} mm of half`);
  }

  if (!quiet) console.log('D. heights and coursing');
  const hs = S.map((b) => b.H);
  ok(Math.min(...hs) === 50 && Math.max(...hs) === 113 && 113 / 50 > 2, 'heights run from 50 to 113 mm, a factor of more than two');
  ok(near(E.coursesTo(65, 10, 300), 4), 'UK: four courses of 75 make 300');
  ok(near(3 * 65 + 2 * 10, 215), 'UK: 3 x 65 + 2 x 10 = 215');
  ok(near(3 * 50 + 2 * 10, 170), 'Waal: three courses make 170');
  ok(near(E.coursesTo(52, 10.5, 1000), 16), 'DF: 52 + 10.5 = 62.5, sixteen to the metre');
  ok(Math.round(E.coursesTo(71, 12.3, 1000)) === 12, 'NF: 71 + 12.3, twelve to the metre');
  ok(3 * (54 + 12) <= 200 && 3 * (54 + 13) >= 200, 'Denmark: three courses of 66 to 67 come to about 200');

  if (!quiet) console.log('E. the figures in the prose');
  says('A British brick is 215 by 102.5 by 65 millimetres.');
  says('the Danish with 228, 108 and a 12 mm joint');
  says('and runs from 50 to 113 mm');
  says('2 × 102.5 + 10 = 215');
  says('Seventeen principal formats from twelve countries. Fourteen of them come with a joint named in the sources read, and in thirteen of those');
  says('10 mm in Britain, Germany, Russia, China, the Netherlands, India (the modular brick) and Australia, 12 mm in Denmark, ⅜ inch (9.5 mm) in the United States');
  says("The sources for Sweden's brick, Japan's and India's non-modular one name no joint, and all three leave exactly 10");
  says('which leaves 10 mm while its brick association recommends 12, a miss of 2 mm');
  says('(3 × 3⅝ + 2 × ⅜ = 11⅝)');
  says('if each joint may be anything from 6 to 15 mm');
  says('the first straight joint arrives about 2.3 m from the corner');
  says("opening the header courses' perpends to 12.5 mm takes up the difference");
  says('may average anywhere from 211 to 219 mm under tolerance class T2');
  says('two headers and a joint come to 320 mm against a stretcher of 240');
  says('the header perpends would need to be 30 mm less than nothing');
  says('The first straight joint is 0.24 m from the corner');
  says('That brick sits 80 mm below the gold line on the plane and 70 below even the dashed line');
  says('a relation that sixteen other principal formats obey');
  says('while length minus two widths stays between 9.5 and 12'); ok(Math.min(...S.map((b) => E.impliedJoint(b.L, b.W))).toFixed(1) === '9.5' && Math.max(...S.map((b) => E.impliedJoint(b.L, b.W))) === 12, 'principal formats leave 9.5 to 12');
  ok(html.includes('the US and six more countries obeys'), 'meta description: the US and six more countries'); ok(countries.size - 6 === 6, 'UK plus five named plus six more is twelve');
  ok(S.filter((b) => b.id !== 'cn').length === 16, '...sixteen: the standards other than China');
  says('in Britain 65 + 10 = 75 mm, four courses to 300 mm');
  says('(3 × 65 + 2 × 10 = 215)');
  says('Three Dutch Waal courses make 170 mm');
  says('Nine less two widths of 4¼ leaves half an inch, 12.7 mm');
  ok(near(9 - 2 * 4.25, 0.5) && near(0.5 * 25.4, 12.7), '9 - 2 x 4 1/4 = 1/2 in = 12.7 mm');
  says('4⅜, which leaves a quarter inch, 6.35 mm'); ok(near(9 - 2 * 4.375, 0.25) && near(0.25 * 25.4, 6.35), '9 - 2 x 4 3/8 = 1/4 in');
  says('went back to nine by 4¼, half an inch again'); ok(near(E.impliedJoint(f('e1725').L, f('e1725').W), 12.7, 1e-9), '1725 leaves 12.7 mm');
  says('set minimums of 8½ by 4 inches, half an inch once more'); ok(near(8.5 - 8, 0.5), '8 1/2 - 2 x 4 = 1/2');
  says('two widths of 4½ are exactly nine'); ok(near(E.impliedJoint(f('eb1911').L, f('eb1911').W), 0, 1e-9), 'Britannica leaves 0');
  ok(['e1571', 'e1625', 'e1725', 'e1777'].every((id) => E.impliedJoint(f(id).L, f(id).W) > 6) && E.impliedJoint(f('eb1911').L, f('eb1911').W) === 0, 'of the five English sizes only Britannica leaves no joint');
  ok(['harappa', 'eridu'].every((id) => near(E.impliedJoint(f(id).L, f(id).W), 0)), 'the ancient bricks are exactly two widths long');
  says('Germany\'s brick industry makes the same 240 by 115 in three standard heights, 52, 71 and 113 mm');
  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(), 'bricks-'));
  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 p = join(tmp, `engine-m${i++}.mjs`);
    writeFileSync(p, engineSrc.replace(from, to));
    let r;
    try { r = await checks(pathToFileURL(p).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);
