// verify-the-pump-that-throws-its-water-away.mjs
//
// Recomputes every number /strata/the-pump-that-throws-its-water-away/ prints, from the same
// engine.js and compare.js the page runs, and from the transcribed 1941 table.
//
//   node research/the-pump-that-throws-its-water-away/verify-the-pump-that-throws-its-water-away.mjs
//   node research/the-pump-that-throws-its-water-away/verify-the-pump-that-throws-its-water-away.mjs --mutate
//
// --mutate plants a fault behind each class of assertion (energy leaking at the waste valve, a
// wrong wave speed, a doctored row of the 1941 table, a figure changed in the prose) and requires
// the suite to go red on every one. An assertion that cannot fail is a sentence, not a check.
//
// Run from outside a checkout, it fetches the served copies of its inputs from the site first and
// prints every URL it fetched. Inside a checkout it fetches nothing.
//
// WHAT THIS DOES NOT CHECK: that the transcription of the 1941 Table 2 matches the scan (that was
// done by eye against page images, see research/the-pump-that-throws-its-water-away/sources/);
// that the handbook coefficients in engine.js describe the 1941 rig; or any quotation's wording
// against its source. It checks arithmetic, the simulation, and that the page says what they say.

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

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '../..');
const REL = 'public/strata/the-pump-that-throws-its-water-away';
const PAGE = join(ROOT, REL);
const ORIGIN = process.env.AW_ORIGIN || 'https://artwaste.land';
const SITE = `${ORIGIN}/strata/the-pump-that-throws-its-water-away`;
const FILES = ['index.html', 'engine.js', 'compare.js', 'app.js', 'data/comparison.json', 'data/lansford_dugan_1941_table2_performance.csv'];

let fetched = 0;
for (const f of FILES) {
  const path = join(PAGE, f);
  if (existsSync(path)) continue;
  if (!fetched) console.log('running outside a checkout; fetching the inputs this check reads:');
  // The trailing slash matters: /index.html answers with a redirect on this site.
  const url = f === 'index.html' ? `${SITE}/` : `${SITE}/${f}`;
  const res = await fetch(url);
  if (!res.ok) { console.error(`  ${url} -> HTTP ${res.status}. Cannot continue.`); process.exit(1); }
  const buf = Buffer.from(await res.arrayBuffer());
  if (!buf.length) { console.error(`  ${url} -> zero bytes. Cannot continue.`); process.exit(1); }
  mkdirSync(dirname(path), { recursive: true });
  writeFileSync(path, buf);
  console.log(`  ${url}  (${buf.length} bytes)`);
  fetched++;
}

const MUTATE = process.argv.includes('--mutate');

// ── the suite, parameterised by where it reads its inputs, so a mutation can swap one ──────
async function suite(dir, { quiet = false } = {}) {
  const fails = [];
  let n = 0;
  const check = (cond, what) => { n++; if (!cond) fails.push(what); };
  const near = (got, want, tol, what) => { n++; if (!(Math.abs(got - want) <= tol)) fails.push(`${what}: got ${got}, want ${want} ± ${tol}`); };

  const bust = `?v=${Math.random()}`;
  const E = await import(pathToFileURL(join(dir, 'engine.js')).href + bust);
  const C = await import(pathToFileURL(join(dir, 'compare.js')).href + bust);
  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(/\s+/g, ' ');
  const csv = readFileSync(join(dir, 'data/lansford_dugan_1941_table2_performance.csv'), 'utf8');
  const committed = JSON.parse(readFileSync(join(dir, 'data/comparison.json'), 'utf8'));
  const says = (s, what) => check(text.includes(s), `page says "${s}" (${what})`);

  // 1. The energy ledger closes, and mass is conserved, across the range the sliders reach.
  const PIPES = { steel: 1356, pvc: E.waveSpeed({ D: 0.0524, e: 0.0039, E: 3.0e9 }), hdpe: E.waveSpeed({ D: 0.0524, e: 0.0039, E: 0.8e9 }) };
  let worstPump = 0, worstIdle = 0, ran = 0, worstNode = 0;
  for (const Hs of [1, 2.8, 6]) for (const hd of [6, 15, 40, 100]) for (const vc of [0.4, 0.89, 1.6]) for (const a of Object.values(PIPES)) {
    if (hd <= Hs * 1.5) continue;
    const o = E.steadyState({ Hs, hd, vc, a });
    if (!o.steady) continue;
    ran++;
    const res = Math.abs(o.ledger.residual / o.ledger.in);
    if (o.etaR > 0.05) worstPump = Math.max(worstPump, res); else worstIdle = Math.max(worstIdle, res);
    const L = o.ledger;
    check([L.lift, L.waste, L.friction, L.entrance, L.dvalve].every((x) => x >= -1e-9 * L.in), `ledger terms non-negative at Hs=${Hs} hd=${hd} vc=${vc}`);
    worstNode = Math.max(worstNode, Math.abs(o.volumes.nodeResidual / o.volumes.in));
    // Energy cannot be made: q(h-H) <= W H, so the Rankine form stays below one; the test-code form is never smaller.
    check(o.etaR < 1 && o.etaD < 1 && o.etaD >= o.etaR - 1e-12, `efficiencies ordered and below one at Hs=${Hs} hd=${hd} vc=${vc}`);
  }
  check(ran >= 60, `the ledger sweep actually ran (${ran} steady settings)`);
  check(worstPump < 5e-3, `ledger within half a per cent wherever the ram pumps (worst ${worstPump.toExponential(2)})`);
  check(worstIdle < 1.5e-2, `ledger within one and a half per cent where it only churns (worst ${worstIdle.toExponential(2)})`);
  check(worstNode < 1e-8, `mass conserved at the ram to a part in a billion (worst ${worstNode.toExponential(2)})`);
  const d0 = E.steadyState({});
  check(Math.abs(d0.ledger.residual / d0.ledger.in) < 2e-5, `about a hundred-thousandth at the 1941 settings (${(d0.ledger.residual / d0.ledger.in).toExponential(2)})`);
  // The remainder is the grid's: refine it and it shrinks.
  const coarse = E.steadyState({ Hs: 1, hd: 15, vc: 0.89, a: PIPES.hdpe, N: 16 }), fine = E.steadyState({ Hs: 1, hd: 15, vc: 0.89, a: PIPES.hdpe, N: 128 });
  check(coarse.steady && fine.steady && Math.abs(fine.ledger.residual / fine.ledger.in) < Math.abs(coarse.ledger.residual / coarse.ledger.in) / 10, 'residual shrinks tenfold as the grid is refined eightfold');
  // A transient must not be passed off as a rhythm: this setting was once reported at 127% efficiency.
  const tr = E.steadyState({ Hs: 1, hd: 100, vc: 0.4, tc: 0.01, N: 16 });
  check(!tr.steady || tr.etaR < 1, 'the former 127% transient is refused or honest');

  // 2. The rig and its hammer.
  const D = E.DEFAULTS;
  near(D.L, 54.8 * C.FT, 0.01, 'drive pipe length is the bulletin 54.8 ft');
  near(Math.PI * D.D * D.D / 4, 0.0233 * C.FT * C.FT, 2e-5, 'drive pipe area is the bulletin 0.0233 sq ft');
  near(D.a, 4450 * C.FT, 1, 'wave speed is the bulletin 4450 ft/s');
  near(D.Hs, 9.2 * C.FT, 0.01, 'supply head is 9.2 ft');
  near(D.vc, 2.93 * C.FT, 0.005, 'closing speed is Series 2, 2.93 ft/s');
  check(D.tc === C.CLOSURE[2].tc, 'default closure time is the measured Series 2 value');
  const surge = 2 * D.L / D.a;
  says(`2L/a = ${surge.toFixed(4)} seconds`, 'surge round trip');
  const r = E.makeRam({}); near(2 * D.N * r.dt, surge, 1e-12, 'grid step makes the surge period exact');
  const J = E.joukowskyHead(D.a, D.vc);
  says(`about ${Math.round(J)} m of water`, 'Joukowsky head at the default speed');
  near(E.waveSpeed({ D: 0.0524, e: 0.0039, E: 200e9 }), 1400, 60, 'Korteweg for the steel pipe is near the bulletin wave speed');
  check(PIPES.hdpe < 300 && PIPES.pvc < 500, `plastic wave speeds are a few hundred m/s (${PIPES.pvc.toFixed(0)}, ${PIPES.hdpe.toFixed(0)})`);
  // The plastic-pipe claim: past the hammer head, delivery collapses; the steel pipe keeps pumping.
  const Jp = E.joukowskyHead(PIPES.hdpe, D.vc);
  const hdHigh = Math.round(Jp * 1.5);
  const steel = E.steadyState({ hd: hdHigh }), poly = E.steadyState({ hd: hdHigh, a: PIPES.hdpe });
  check(steel.running && steel.q > 0, 'steel pipe pumps at 1.5 times the polyethylene hammer head');
  check(!poly.running || poly.q < 0.05 * steel.q, `polyethylene delivers under 5% of steel there (${poly.running ? (poly.q / steel.q).toFixed(3) : 'stalled'})`);
  // The stall toward twice the fall.
  check(!E.steadyState({ hd: 1.8 * D.Hs }).running, 'default ram stalls with the tank below twice the fall');
  check(E.steadyState({ hd: 15 }).running, 'default ram runs at the default 15 m');
  // The body's peak barely exceeds the delivery head (the prose's "barely rises above").
  {
    const rr = E.makeRam({}); let peak = -1e9;
    while (rr.s.t < 20) { rr.step(); if (rr.s.t > 10) peak = Math.max(peak, rr.s.hb); }
    check(peak < D.hd * 1.05 && J > 5 * D.hd, `peak body head ${peak.toFixed(2)} m against a hammer head of ${J.toFixed(0)} m`);
  }

  // 3. Eytelwein's three numbers, from his four.
  const M = 1646, m = 863, H = 117.25, h = 189.75;
  const ey = [m * (H + h) / (M * H), m * (H + h) / ((M + m) * H), m * h / (M * H)];
  const printed = [1.3728, 0.9006, 0.8485];
  ey.forEach((v, i) => near(Number(v.toFixed(4)), printed[i], 1e-9, `Eytelwein form ${i + 1} recomputes to his printed ${printed[i]}`));
  ['ey1', 'ey2', 'ey3'].forEach((id, i) => check(new RegExp(`id="${id}">${printed[i].toFixed(4).replace('.', '\\.')}<`).test(html), `page shows ${printed[i]}`));
  says(`${Math.floor(ey[0] * 100)} per cent`, 'the absurd form as a percentage');

  // 4. The 1941 table, from its own printed flows.
  const rows = C.parseTable(csv);
  check(rows.length === 163, `163 rows (${rows.length})`);
  says('163 measured runs', 'row count in the heading');
  const by = Object.fromEntries(rows.map((x) => [x.test, x]));
  const eff = (t) => C.measuredEfficiencies(by[t]);
  says(`${eff('711').rankine.toFixed(1)}% by its own printed flows and ${eff('711').testCode.toFixed(1)}% in the test-code form`, 'test 711');
  says(`has ${eff('703').rankine.toFixed(1)}% and ${eff('703').testCode.toFixed(1)}%`, 'test 703');
  const gaps = rows.map((x) => Math.abs(C.measuredEfficiencies(x).rankine - x.etaR_printed));
  const off = gaps.filter((g) => g > 1).length;
  says(`in ${['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty'][off]} of its rows the printed efficiency disagrees with the printed flows by more than one point (at most ${Math.max(...gaps).toFixed(1)})`, 'inconsistent rows');
  const heads = rows.map((x) => x.h);
  says(`${Math.min(...heads)} to ${Math.max(...heads)} ft`, 'range of delivery heads');
  says(`2-inch ram, lifting to ${by['711'].h} ft from a ${by['711'].H} ft fall`, 'test 711 heads');

  // 5. The simulation against 1941: recompute everything and require the committed file to match.
  const compared = rows.map(C.compareRow);
  const fresh = { source: committed.source, rows: compared, series: C.summarise(compared) };
  check(JSON.stringify(fresh) === JSON.stringify(committed), 'comparison.json is exactly what engine.js and the table produce');
  const tbl = html.match(/<!--TABLE:start-->([\s\S]*?)<!--TABLE:end-->/);
  check(tbl && tbl[1] === C.tableHtml(fresh.series), 'the table on the page is generated from the same numbers');
  const S = Object.fromEntries(fresh.series.map((s) => [s.series, s]));
  check(Math.abs(S[1].maxModelRankine - S[1].maxMeasRankine) < 2 && Math.abs(S[2].maxModelRankine - S[2].maxMeasRankine) < 2, 'Series 1 and 2 best efficiency within two points');
  says('lands within two points of the measured best', 'prose for the above');
  const e12 = [S[1], S[2]].flatMap((s) => [s.medianAbsErrPct.Qc, s.medianAbsErrPct.qc]);
  says(`within about ${Math.round(Math.min(...e12))} to ${Math.round(Math.max(...e12))} per cent`, 'per-beat error range, Series 1 and 2');
  says(`Series 6 its efficiency averages ${Math.round(S[6].meanRankineGap)} points above`, 'Series 6 mean gap');
  check([3, 4, 5, 6].every((k) => S[k].meanRankineGap > 5), 'Series 3 to 6 all overstated by more than five points');
  const simd = compared.filter((x) => x.model);
  const fast = simd.filter((x) => x.model.tc < x.meas.tc).length;
  says(`in ${fast} of the ${simd.length} tests it could settle into a steady beat (one Series 5 test never did`, 'beats too fast');
  check(compared.length - simd.length === 1 && compared.find((x) => !x.model).series === 5, 'exactly one test, in Series 5, never settles');
  const t711 = compared.find((x) => x.test === '711');
  says(`(${eff('711').rankine.toFixed(1)}% at 24.5 ft) while the simulation stays level near ${Math.round(t711.model.rankine)}%`, 'low-lift miss');
  check(compared.every((x) => !x.model || Math.abs(x.model.residual) < 5e-3), 'every simulated 1941 row closes its own ledger to half a per cent');

  // 6. Dates and small arithmetic in the prose.
  says(`a hundred and thirty-nine years earlier`, '1941 - 1802'); check(1941 - 1802 === 139, '139');
  check(!/—/.test(text.replace(/“[^”]*”/g, '')), 'no em dash in the page prose outside quotations');

  if (!quiet) {
    console.log(`energy ledger over ${ran} steady settings: worst ${worstPump.toExponential(2)} pumping, ${worstIdle.toExponential(2)} idle; node mass ${worstNode.toExponential(2)}`);
    console.log(`Joukowsky head at ${D.vc.toFixed(3)} m/s in the 1941 pipe: ${J.toFixed(2)} m; polyethylene ${Jp.toFixed(1)} m`);
    console.log(`Eytelwein: ${ey.map((v) => v.toFixed(4)).join(', ')}`);
    for (const s of fresh.series) console.log(`series ${s.series}: best measured ${s.maxMeasRankine}%, simulated ${s.maxModelRankine}%, mean gap ${s.meanRankineGap}`);
  }
  return { n, fails };
}

const { n, fails } = await suite(PAGE);
if (fails.length) {
  console.log(`\n✗ ${fails.length} of ${n} assertions failed:`);
  for (const f of fails) console.log('  - ' + f);
  process.exit(1);
}
console.log(`\n✓ ${n} assertions passed`);

if (MUTATE) {
  // Each mutation copies the inputs to a scratch directory, plants one fault, and requires red.
  const mutations = [
    ['energy leaks at the waste valve', 'engine.js', (s) => s.replace("s.Ewaste += RHO * G * tz('fw');", "s.Ewaste += 0.97 * RHO * G * tz('fw');")],
    ['wrong wave speed in the rig', 'engine.js', (s) => s.replace('a: 1356,', 'a: 1300,')],
    ['a doctored row of the 1941 table', 'data/lansford_dugan_1941_table2_performance.csv', (s) => s.replace('1,2-in,703,9.2,4.48,0.0269,left,103.5,185.2,9.9,', '1,2-in,703,9.2,4.48,0.0269,left,103.5,185.2,10.9,')],
    ['a figure changed in the prose', 'index.html', (s) => s.replace('0.8485</b>', '0.8845</b>')],
    ['the table edited by hand', 'index.html', (s) => s.replace(/(<!--TABLE:start-->[\s\S]*?)55\.9%/, '$158.9%')],
  ];
  let bad = 0;
  for (const [what, file, f] of mutations) {
    const tmp = mkdtempSync(join(tmpdir(), 'ram-mut-'));
    for (const g of FILES) { mkdirSync(dirname(join(tmp, g)), { recursive: true }); copyFileSync(join(PAGE, g), join(tmp, g)); }
    const before = readFileSync(join(tmp, file), 'utf8'), after = f(before);
    if (after === before) { console.log(`  ✗ mutation "${what}" did not apply`); bad++; rmSync(tmp, { recursive: true }); continue; }
    writeFileSync(join(tmp, file), after);
    const res = await suite(tmp, { quiet: true });
    rmSync(tmp, { recursive: true });
    if (res.fails.length) console.log(`  ✓ red under "${what}" (${res.fails.length} failing, e.g. ${res.fails[0].slice(0, 90)})`);
    else { console.log(`  ✗ STILL GREEN under "${what}"`); bad++; }
  }
  if (bad) { console.log(`\n✗ ${bad} mutation(s) not caught`); process.exit(1); }
  console.log(`\n✓ all ${mutations.length} mutations caught`);
}
