#!/usr/bin/env node
// verify-how-deep-can-fish-live.mjs: checks /strata/how-deep-can-fish-live/ ("A Line Drawn Ahead of the Fish").
//
//   node verify-how-deep-can-fish-live.mjs            # engine, references, digitizing, intervals, every quoted figure
//   node verify-how-deep-can-fish-live.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
// ./how-deep-can-fish-live-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// What it checks:
//  A. the seawater equation (EOS-80) against the check values printed by UNESCO (Tech. Pap. 44, p. 22);
//  B. the engine's pressure, seawater compression and air figures against independent libraries
//     (TEOS-10 via gsw, the seawater package, CoolProp), tabulated below;
//  C. the digitized fish: a line refitted to the twelve 2014 points reproduces the equation printed
//     in the 2014 figure (326 + 0.0916 x depth), and with the Kermadec snailfish, 320 + 0.0953 x depth;
//  D. Student's t and every fit and 95% interval against numpy/scipy, and each interval again by a
//     brute-force scan done here;
//  E. every figure the prose quotes, recomputed and found in its own sentence on the page.
// What it does NOT check: that the sources say what the page says they say (the words relied on are
// kept with each source in assay/sources/how-deep-can-fish-live.json), or how faithfully a marker
// centre was located in a figure beyond what C can see.

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 = 'how-deep-can-fish-live';
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}`);

// ── Independent references, generated by research/how-deep-can-fish-live/reference.py (gsw 3.6.23,
// seawater 3.3.5, CoolProp 8.0.0) and intervals.py (numpy + scipy, 95% intervals by a 0.25 m scan),
// and the points from digitize.py. Columns: depth m, pressure dbar (TEOS-10), pressure dbar (Saunders),
// shrink (TEOS-10), shrink (EOS-80, seawater package), air density ratio (CoolProp).
const REF = [[0,0,0,0,0,1],[500,504.04,504.21,0.002288,0.002291,51.83],[1000,1009.3,1009.55,0.004546,0.004553,103.4],[1500,1515.77,1516.04,0.006773,0.006784,153.13],[2000,2023.44,2023.69,0.00897,0.008987,198.75],[2500,2532.3,2532.49,0.011137,0.011162,239.19],[3000,3042.34,3042.46,0.013275,0.013308,274.44],[3500,3553.55,3553.61,0.015383,0.015427,305.06],[4000,4065.92,4065.94,0.017462,0.017519,331.77],[4500,4579.44,4579.47,0.019513,0.019584,355.25],[5000,5094.09,5094.2,0.021536,0.021624,376.09],[5500,5609.88,5610.13,0.02353,0.023637,394.75],[6000,6126.78,6127.29,0.025497,0.025626,411.6],[6500,6644.78,6645.67,0.027437,0.02759,426.95],[7000,7163.89,7165.29,0.029351,0.02953,441.03],[7500,7684.08,7686.15,0.031238,0.031445,454.01],[8000,8205.34,8208.27,0.033099,0.033337,466.07],[8500,8727.68,8731.65,0.034936,0.035206,477.31],[9000,9251.06,9256.3,0.036747,0.037053,487.84],[9500,9775.5,9782.23,0.038534,0.038877,497.75],[10000,10300.98,10309.45,0.040298,0.040679,507.11],[10500,10827.48,10837.98,0.042039,0.042459,515.97],[11000,11355,11367.81,0.043757,0.044218,524.39]];
const SCIPY_T975 = {"3":3.18244631,"4":2.77644511,"5":2.57058184,"6":2.44691185,"7":2.36462425,"8":2.30600414,"9":2.26215716,"10":2.22813885,"11":2.20098516,"12":2.17881283,"13":2.16036866,"14":2.14478669,"15":2.13144955,"16":2.1199053,"17":2.10981558,"18":2.10092204,"19":2.09302405,"20":2.08596345,"21":2.07961384,"22":2.07387307,"23":2.06865761,"24":2.06389856,"25":2.05953855,"26":2.05552944,"27":2.05183052,"28":2.04840714,"29":2.04522964,"30":2.04227246};
const SCIPY_SETS = {"before":{"n":12,"a":325.206445,"b":0.092387401,"lo":7410.5,"hi":9758},"kermadec":{"n":13,"a":320.779697,"b":0.095159111,"lo":7746,"hi":8701},"snailfish":{"n":20,"a":317.096086,"b":0.097922863,"lo":7831,"hi":8168.75},"snailonly":{"n":8,"a":587.261695,"b":0.060660778,"lo":8034.25,"hi":9502.75},"all":{"n":27,"a":309.011022,"b":0.097414937,"lo":7830.75,"hi":8443}};
const DIGITIZED = {"pre":[[502,389],[502,362],[795,391],[1306,462],[1306,435],[1854,506],[2091,523],[2109,508],[2109,496],[2200,540],[2873,561],[3000,637]],"later":[[6453,984],[6941,1011],[7085,1017],[7197,1025],[7482,1039],[7492,1063],[7898,1059]],"others":[[3564,588],[4203,725],[4440,660],[5258,754],[4822,692],[5057,861],[5057,838]]};

// UNESCO Tech. Pap. Mar. Sci. 44 (1983), p. 22 check values (as quoted in the seawater package's
// docstrings): [s, t, p dbar, density kg/m3, secant bulk modulus bar].
const UNESCO = [
  [0, 0, 0, 999.842594, 19652.21], [0, 0, 10000, 1045.33710972, 22977.2115],
  [0, 30, 0, 995.65113374, 22336.0044572], [0, 30, 10000, 1036.03148891, 25656.8196222],
  [35, 0, 0, 1028.10633141, 21582.27006823], [35, 0, 10000, 1070.95838408, 24991.99729129],
  [35, 30, 0, 1021.72863949, 23924.21823158], [35, 30, 10000, 1060.55058771, 27318.32472464],
];

const MUTANTS = [
  ['pure-water density term dropped', '999.842594, 6.793952e-2', '999.842594, 0'],
  ['bulk modulus ignores pressure', 'return K0 + (A + B * p) * p;', 'return K0;'],
  ['Saunders latitude term doubled', 'const c1 = 5.92e-3 + x * x * 5.25e-3;', 'const c1 = 5.92e-3 + x * x * 10.5e-3;'],
  ['one digitized fish moved 50 mOsm', '[2873, 561]', '[2873, 611]'],
  ['Kermadec snailfish read as 941', 'export const KERMADEC_2014 = [7000, 991];', 'export const KERMADEC_2014 = [7000, 941];'],
  ['one-sided t (97.5% read as 95%)', 'if (tCdf(mid, df) < 0.975)', 'if (tCdf(mid, df) < 0.95)'],
  ['interval without the 1/n term', 'const A = b * b - k / sxx, B = 2 * b * c0, C = c0 * c0 - k / n;', 'const A = b * b - k / sxx, B = 2 * b * c0, C = c0 * c0;'],
  ['seawater at 1,000', 'export const SEAWATER_MOSM = 1100;', 'export const SEAWATER_MOSM = 1000;'],
];

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(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/\s+/g, ' ');
  const sentences = text.split(/(?<=[.:;?!])\s+/);
  // the records table, one row per line, cells separated by |
  const tableRows = (html.match(/<tbody>[\s\S]*?<\/tbody>/) || [''])[0].replace(/<\/td>/g, ' |').replace(/<\/tr>/g, '\n').replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ');
  // a figure must be in the same sentence as its context words
  const says = (fig, ctx, label) => ok(sentences.some((s) => s.includes(fig) && ctx.every((c) => s.includes(c))),
    `page says "${fig}" beside ${ctx.map((c) => `"${c}"`).join(', ')}${label ? ' (' + label + ')' : ''}`);
  const near = (a, b, tol) => Math.abs(a - b) <= tol;
  const n0 = (x) => Math.round(x).toLocaleString('en-GB');

  if (!quiet) console.log('A. EOS-80 against the UNESCO check values');
  for (const [s, t, p, rho, K] of UNESCO) {
    ok(near(E.dens(s, t, p), rho, 5e-7), `density(${s}, ${t} C, ${p} dbar) = ${rho}`);
    ok(near(E.secantBulkModulusBar(s, t, p), K, 5e-6), `bulk modulus(${s}, ${t} C, ${p} dbar) = ${K}`);
  }

  if (!quiet) console.log('B. pressure, compression and air against independent libraries');
  let worstP = 0, worstS80 = 0, worstS10 = 0;
  for (const [z, pG, pS, s10, s80, air] of REF) {
    worstP = Math.max(worstP, Math.abs(E.pressureDbar(z) - pS));
    worstS80 = Math.max(worstS80, Math.abs(E.waterShrink(z) - s80));
    worstS10 = Math.max(worstS10, Math.abs(E.waterShrink(z) - s10));
    if (z > 0) ok(near(E.pressureDbar(z), pG, 0.0015 * pG), `${z} m: pressure within 0.15% of TEOS-10 (${pG} dbar)`);
    ok(near(E.airReal(z), air, 1e-9), `${z} m: air ratio = CoolProp ${air}`);
  }
  ok(worstP < 0.01, `pressure = Saunders 1981 (seawater.pres) to ${worstP.toFixed(4)} dbar everywhere`);
  ok(worstS80 < 2e-6, `compression = EOS-80 (seawater.dens) to ${worstS80.toExponential(1)} everywhere`);
  ok(worstS10 < 5e-4, `compression within 0.05 percentage points of TEOS-10 everywhere (worst ${(100 * worstS10).toFixed(3)})`);
  const at = REF.find((r) => r[0] === 8500);
  ok(near(E.waterShrink(8500), at[3], 3e-4), 'at 8,500 m, EOS-80 and TEOS-10 agree within 0.03 percentage points');

  if (!quiet) console.log('C. the digitized fish reproduce the equations printed in the 2014 figure');
  ok(JSON.stringify(E.PRE2014) === JSON.stringify(DIGITIZED.pre), 'engine twelve = digitize.py output');
  ok(JSON.stringify(E.LATER_SNAILFISH.map((p) => [p.depth, p.osm])) === JSON.stringify(DIGITIZED.later), 'engine later snailfish = digitize.py output');
  ok(JSON.stringify(E.OTHER_FAMILIES.map((p) => [p.depth, p.osm])) === JSON.stringify(DIGITIZED.others), 'engine rattails and eelpouts = digitize.py output');
  const F12 = E.fit(E.PRE2014), F13 = E.fit([...E.PRE2014, E.KERMADEC_2014]);
  ok(E.PRE2014.length === 12 && near(F12.a, 326, 5) && near(F12.b, 0.0916, 0.002), `twelve points refit ${F12.a.toFixed(1)} + ${F12.b.toFixed(4)} x, printed 326 + 0.0916 x`);
  ok(near(F13.a, 320, 5) && near(F13.b, 0.0953, 0.002), `with the snailfish ${F13.a.toFixed(1)} + ${F13.b.toFixed(4)} x, printed 320 + 0.0953 x`);
  ok(near((1100 - 326) / 0.0916, 8450, 1), 'the printed black equation reaches 1,100 at 8,450 m');
  ok(near((1100 - 320) / 0.0953, 8185, 1), 'the printed red equation reaches 1,100 at 8,185 m, "about 8,200"');
  ok(E.KERMADEC_2014[0] === 7000 && E.KERMADEC_2014[1] === 991 && E.SEAWATER_MOSM === 1100, 'Kermadec 991 at 7,000 m; seawater 1,100 (the abstract)');

  if (!quiet) console.log("D. Student's t, fits and intervals");
  let worstT = 0;
  for (const [df, t] of Object.entries(SCIPY_T975)) worstT = Math.max(worstT, Math.abs(E.t975(+df) - t));
  ok(worstT < 1e-6, `t(0.975) for 3 to 30 degrees of freedom = scipy to ${worstT.toExponential(1)}`);
  const cross = {};
  for (const [name, S] of Object.entries(SCIPY_SETS)) {
    const F = E.fit(E.SETS[name].points()), c = E.crossing(F);
    cross[name] = c;
    ok(F.n === S.n && near(F.a, S.a, 1e-6) && near(F.b, S.b, 1e-9), `${name}: ${S.n} fish, line = scipy linregress`);
    ok(c.lo !== null && near(c.lo, S.lo, 0.5) && near(c.hi, S.hi, 0.5), `${name}: 95% interval ${n0(c.lo)} to ${n0(c.hi)} = scipy scan`);
    // and again by a scan here: every depth at which 1,100 lies inside the line's 95% band
    let lo = null, hi = null;
    for (let x = 5000; x <= 12000; x += 0.5) {
      const band = F.t * F.s * Math.sqrt(1 / F.n + (x - F.xb) ** 2 / F.sxx);
      if (Math.abs(F.a + F.b * x - E.SEAWATER_MOSM) <= band) { if (lo === null) lo = x; hi = x; }
    }
    ok(lo !== null && near(c.lo, lo, 0.6) && near(c.hi, hi, 0.6), `${name}: the same interval by a 0.5 m scan here`);
  }

  if (!quiet) console.log('E. every figure the prose quotes');
  const z = 8336;
  says(`${n0(E.atmospheres(z))} atmospheres`, ['8,336 m', 'pressure']);
  says(`about ${n0(1000 * (1 - E.waterShrink(z)))} millilitres`, ['litre of deep seawater']);
  says(`${(100 * E.waterShrink(z)).toFixed(2)} percent`, ['shrunk']);
  says(`${n0(E.airBoyle(z))}-fold`, ["Boyle's law"]);
  says(`${n0(E.airReal(z))}-fold`, ['real air']);
  ok(Math.round(1000 / E.airReal(z)) === 2, 'roughly two millilitres of air'); says('to roughly two millilitres', ['real air']);
  ok(near(100 * E.waterShrink(z), 3.5, 0.05), 'about 3.5 percent'); says('seawater has shrunk by about 3.5 percent', ['8,336 metres', 'deepest fish ever seen'], 'the dek');
  ok(E.atmospheres(11000) > 1000, 'the deepest trenches (11,000 m): more than a thousand atmospheres'); says('under more than a thousand', ['deepest trenches']);
  ok(near((1100 - F13.a) / F13.b, 8200, 50), 'the thirteen-point line crosses near 8,200'); says('would stop near 8,200 metres', ['7,000'], 'the dek'); says('That is the “8,200 m” of the abstract', []);
  says('96.53 percent water', ['nine species']);
  const c = cross;
  says(`${n0(c.before.depth)} m`, ['95% interval', `${n0(c.before.lo)} to ${n0(c.before.hi)} m`], 'twelve fish');
  says(`slope of ${F12.b.toFixed(4)}`, [`lands at ${n0(c.before.depth)}`]);
  says(`moves the answer ${Math.round(8450 - c.before.depth)} metres`, []);
  const p7 = E.predict(F12, 7000);
  says(`${n0(p7.osm)} mOsm/kg, give or take ${n0(p7.pm)}`, ['7,000 m']);
  says(`crossing moves to ${n0(c.kermadec.depth)} m`, [`${n0(c.kermadec.lo)} to ${n0(c.kermadec.hi)} m`]);
  says(`${n0(c.snailfish.depth)} m (${n0(c.snailfish.lo)} to ${n0(c.snailfish.hi)})`, ['twenty points']);
  ok(8336 > c.snailfish.hi, 'the 8,336 m fish is outside the twenty-fish interval, as the prose says');
  const Fs = E.fit(E.SETS.snailonly.points());
  says(`${n0(c.snailonly.depth)} m (${n0(c.snailonly.lo)} to ${n0(c.snailonly.hi)})`, ['8,336 m sits inside']);
  ok(8336 >= c.snailonly.lo && 8336 <= c.snailonly.hi, 'the 8,336 m fish is inside the snailfish-alone interval');
  says(`${Fs.b.toFixed(4)} per metre, not ${E.fit(E.SETS.snailfish.points()).b.toFixed(4)}`, ['flatter']);
  const later = E.LATER_SNAILFISH;
  const resid = later.map((p) => p.osm - (F12.a + F12.b * p.depth));
  ok(later.every((p) => Math.abs(p.osm - E.predict(F12, p.depth).osm) <= E.predict(F12, p.depth).pm), 'all seven later snailfish inside the twelve-fish prediction band');
  says(`by ${Math.round(Math.min(...resid))} to ${Math.round(Math.max(...resid))} mOsm/kg`, ['above the old line']);
  ok(resid.every((r) => r > 0), '...and all seven are above it');
  says(`${n0(Math.min(...later.map((p) => p.depth)))} to ${n0(Math.max(...later.map((p) => p.depth)))} m`, ['not at the 7,000 m of the 2014 sample']);
  says(`${Math.round(F12.a * 10) / 10} + ${F12.b.toFixed(4)} × depth`, ['printed 326 + 0.0916']);
  says(`${(Math.round(F13.a * 10) / 10).toFixed(1)} + ${F13.b.toFixed(4)}`, ['printed 320 + 0.0953']);
  const centres = Object.values(c).map((x) => x.depth);
  const lo = Math.min(...centres), hi = Math.max(...centres);
  says(`from ${n0(lo)} to ${n0(hi)} m, lies within 350 metres`, []);
  ok(centres.every((x) => Math.abs(x - 8336) <= 350), `every central estimate within 350 m of 8,336 (worst ${Math.round(Math.max(...centres.map((x) => Math.abs(x - 8336))))})`);
  ok(E.RECORDS.every((r) => r.depth < 8400) && E.RECORDS.length === 5, 'five records, all shallower than 8,400 m');
  const ROW = { 8370: 'Puerto Rico Trench', 8336: 'Izu-Ogasawara Trench', 8178: 'Pseudoliparis swirei', 8145: 'ethereal snailfish', 8022: 'Japan Trench' };
  for (const r of E.RECORDS) ok(new RegExp(`${n0(r.depth)} m[^|]{0,40}\\|[^|]*${ROW[r.depth]}`).test(tableRows), `records table: ${n0(r.depth)} m on the row naming ${ROW[r.depth]}`);
  says('between 6,824 and 8,336 m', ['Snailfish turned up']); says('from 4,534 to 9,773 m', ['Izu-Ogasawara']);
  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(), 'fishdepth-'));
  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);
