#!/usr/bin/env node

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, '..', '..');
const htmlPath = resolve(root, 'public/strata/the-catapult-under-the-fern/index.html');
const mdPath = resolve(root, 'src/content/strata/the-catapult-under-the-fern.md');
const readmePath = resolve(here, 'README.md');
const verifierPath = fileURLToPath(import.meta.url);
const html = readFileSync(htmlPath, 'utf8');
const frontmatter = readFileSync(mdPath, 'utf8');
const readme = readFileSync(readmePath, 'utf8');
const verifierSource = readFileSync(verifierPath, 'utf8');

const measured = Object.freeze({
  cells: 13,
  cavitationBar: -100,
  cavitationSdBar: 14,
  fastUs: 28.4,
  fastSdUs: 9,
  poreMs: 5.3,
  poreSdMs: 3.5,
  roundedFastUs: 30,
  roundedPoreUs: 5000,
  launchSpeedUpperMps: 10
});

// Table 1, figure 5, section 3.3, and appendix A.4 of Llorens et al. 2016.
const mechanics = Object.freeze({
  widthM: 70e-6,
  heightM: 36e-6,
  lengthM: 26e-6,
  wallM: 7.9e-6,
  n: 13,
  bendingEI: 2.3e-11,
  density: 163,
  viscosity: 1e-3,
  permeability: 1.8e-22,
  youngPa: 6.55e9
});

const failures = [];
let reportCount = 0;

function report(label, ok, detail) {
  reportCount += 1;
  const mark = ok ? 'PASS' : 'FAIL';
  console.log(`${mark.padEnd(4)}  ${label}`);
  if (detail) console.log(`      ${detail}`);
  if (!ok) failures.push(label);
}

function within(value, centre, spread) {
  return Math.abs(value - centre) <= spread;
}

// This pressure conversion goes through SI pascals. The browser uses the direct
// bar-to-megapascal scale factor, so the two routes do not share arithmetic.
function barToMpaThroughSi(bar) {
  const pascals = bar * 100000;
  return pascals / 1000000;
}

// Equation quoted in section 3.3 of Llorens et al. 2016.
function beamPeriodUs(p) {
  const denominator = p.density * p.widthM * p.heightM * (p.n ** 4) * (p.lengthM ** 4);
  const omega = 3.52 * Math.sqrt(p.bendingEI / denominator);
  return (2 * Math.PI / omega) * 1e6;
}

// Appendix A.4 of Llorens et al. 2016.
function poreTimeMs(p) {
  const seconds = p.viscosity * (p.wallM ** 2) /
    ((Math.PI ** 2) * p.permeability * p.youngPa);
  return seconds * 1e3;
}

function normalizedClosure(timeUs, fastUs, poreUs) {
  return 0.40 * (1 - Math.exp(-timeUs / fastUs)) +
    0.60 * (1 - Math.exp(-timeUs / poreUs));
}

function containsAll(source, needles) {
  return needles.every((needle) => source.includes(needle));
}

const pressureMpa = barToMpaThroughSi(measured.cavitationBar);
const pressureSdMpa = Math.abs(barToMpaThroughSi(measured.cavitationSdBar));
report(
  'published cavitation pressure converts to -10.0 ± 1.4 MPa',
  pressureMpa === -10 && pressureSdMpa === 1.4,
  `${measured.cavitationBar} ± ${measured.cavitationSdBar} bar -> ${pressureMpa.toFixed(1)} ± ${pressureSdMpa.toFixed(1)} MPa`
);

const predictedFastUs = beamPeriodUs(mechanics);
report(
  'independent beam-mechanics period meets the published 28.4 ± 9 μs anchor',
  within(predictedFastUs, measured.fastUs, measured.fastSdUs),
  `beam route ${predictedFastUs.toFixed(3)} μs; measured band ${(measured.fastUs - measured.fastSdUs).toFixed(1)} to ${(measured.fastUs + measured.fastSdUs).toFixed(1)} μs`
);

const predictedPoreMs = poreTimeMs(mechanics);
report(
  'independent Darcy-mechanics time meets the published 5.3 ± 3.5 ms anchor',
  within(predictedPoreMs, measured.poreMs, measured.poreSdMs),
  `Darcy route ${predictedPoreMs.toFixed(4)} ms; measured band ${(measured.poreMs - measured.poreSdMs).toFixed(1)} to ${(measured.poreMs + measured.poreSdMs).toFixed(1)} ms`
);

const meanRatio = measured.poreMs * 1000 / measured.fastUs;
const roundedRatio = measured.roundedPoreUs / measured.roundedFastUs;
const modelRatio = predictedPoreMs * 1000 / predictedFastUs;
report(
  'measured means recompute the displayed 186.6-fold separation',
  Math.abs(meanRatio - 186.61971830985917) < 1e-12,
  `${measured.poreMs} ms / ${measured.fastUs} μs = ${meanRatio.toFixed(1)}x`
);
report(
  'rounded abstract values recompute the displayed 166.7-fold separation',
  Math.abs(roundedRatio - 166.66666666666666) < 1e-12,
  `${measured.roundedPoreUs} μs / ${measured.roundedFastUs} μs = ${roundedRatio.toFixed(1)}x; paper wording: about 200`
);
report(
  'two independent mechanics equations reproduce a separation near 200',
  modelRatio >= 100 && Math.abs(modelRatio - 200) < 10,
  `${predictedPoreMs.toFixed(4)} ms / ${predictedFastUs.toFixed(3)} μs = ${modelRatio.toFixed(1)}x`
);

const poisonedStiffness = { ...mechanics, bendingEI: mechanics.bendingEI * 100 };
const poisonedFastUs = beamPeriodUs(poisonedStiffness);
report(
  'control on the control rejects stiffness multiplied by 100',
  !within(poisonedFastUs, measured.fastUs, measured.fastSdUs),
  `REJECTED as intended: ${poisonedFastUs.toFixed(3)} μs is outside the published 19.4 to 37.4 μs band`
);

const poisonedPermeability = { ...mechanics, permeability: mechanics.permeability * 100 };
const poisonedPoreMs = poreTimeMs(poisonedPermeability);
report(
  'control on the control rejects permeability multiplied by 100',
  !within(poisonedPoreMs, measured.poreMs, measured.poreSdMs),
  `REJECTED as intended: ${poisonedPoreMs.toFixed(4)} ms is outside the published 1.8 to 8.8 ms band`
);

const measuredAtOneFastPeriod = normalizedClosure(
  measured.fastUs,
  measured.fastUs,
  measured.poreMs * 1000
);
const collapsedAtOneFastPeriod = normalizedClosure(
  measured.fastUs,
  measured.fastUs,
  30
);
report(
  'the two reader-reachable controls are non-vacuous at one fast period',
  measuredAtOneFastPeriod < 0.30 && collapsedAtOneFastPeriod > 0.60,
  `same normalized load: measured τ closes ${measuredAtOneFastPeriod.toFixed(3)}, collapsed τ closes ${collapsedAtOneFastPeriod.toFixed(3)}`
);

const sliderMinRatio = 0.03 * 1000 / measured.fastUs;
const sliderMaxRatio = 30 * 1000 / measured.fastUs;
report(
  'the pore-time slider reaches both sides of the stated 100-fold criterion',
  sliderMinRatio < 100 && sliderMaxRatio > 100,
  `reachable ratio ${sliderMinRatio.toFixed(2)}x to ${sliderMaxRatio.toFixed(1)}x`
);

const expectedDek = 'The 13-cell annulus measured in Polypodium aureum stores elastic energy as water leaves, cavitates near -100 ± 14 bar, and recoils in about 30 microseconds. Then a roughly 5-millisecond poroelastic relaxation supplies the missing crossbar. Operate both time scales and watch why the trigger alone is not enough.';
const metaMatches = [
  `<title>How Fern Sporangia Catapult Spores</title>`,
  `<meta name="description" content="${expectedDek}" />`,
  `<meta property="og:description" content="${expectedDek}" />`,
  'https://artwaste.land/strata/the-catapult-under-the-fern/',
  'datePublished":"2026-08-25"',
  'dateModified":"2026-08-25"'
];
report(
  'search, share, canonical, and JSON-LD surfaces state the verified page honestly',
  containsAll(html, metaMatches),
  'title, description, OG description, canonical URL, and both dates found'
);

const visibleFigures = [
  '>13</span>',
  '>-100 ± 14 bar</span>',
  '>28.4 ± 9 μs</span>',
  '>5.3 ± 3.5 ms</span>',
  'equal to -10.0 MPa',
  'magnitude of 100 ± 14 bar, which is 10.0 ± 1.4 MPa',
  'up to 10 m/s',
  '30 μs and 5000 μs figures give 166.7×',
  'published mean setting gives 186.6×',
  'at least two orders',
  'normalized 40:60 response',
  'Remove brake, 0.03 ms'
];
report(
  'the rendered scientific figures and qualifications remain present in the HTML',
  containsAll(html, visibleFigures),
  'species count, pressure, times, ratios, launch upper bound, criterion, model split, and control found'
);

const scriptContract = [
  'theoreticalFastUs(P)',
  'theoreticalPoreMs(P)',
  "fmt(fastTheory, 1) + ' μs'",
  "fmt(poreTheory, 2) + ' ms'",
  "fmt(fullRatio, 1) + '×'",
  "fmt(roundedRatio, 1) + '×'",
  'tests.filter(Boolean).length',
  "'REJECTED as intended'"
];
report(
  'the visible check cells are wired to live computations, including poison rejection',
  containsAll(html, scriptContract),
  'all check-output expressions found in the inline script'
);

const jsonLdMatch = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
let jsonLdOk = false;
if (jsonLdMatch) {
  try {
    const article = JSON.parse(jsonLdMatch[1]);
    jsonLdOk = article['@type'] === 'Article' &&
      article.name === 'How Fern Sporangia Catapult Spores' &&
      article.headline === 'The Catapult Under the Fern' &&
      article.description === expectedDek &&
      article.datePublished === '2026-08-25' &&
      article.dateModified === '2026-08-25';
  } catch {
    jsonLdOk = false;
  }
}
report('JSON-LD parses and carries the required Article fields', jsonLdOk);

const frontmatterContract = [
  'title: "The Catapult Under the Fern"',
  'date: 2026-08-25',
  `dek: "${expectedDek}"`,
  'seoTitle: "How Fern Sporangia Catapult Spores"',
  'plain: "This page models the 13-cell spore catapult measured in Polypodium aureum.',
  'seam: "life"',
  'href: "/strata/the-catapult-under-the-fern/"',
  'draft: false'
];
report(
  'frontmatter title, date, dek, SEO title, placard, seam, href, and publish state agree',
  containsAll(frontmatter, frontmatterContract),
  'all required surface fields found'
);

report(
  'the page closes all load-bearing tags',
  /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html),
  'final inline script, body, and html closing tags found'
);

report(
  'no em dash appears in any of the four authored files',
  !html.includes('\u2014') && !frontmatter.includes('\u2014') &&
    !readme.includes('\u2014') && !verifierSource.includes(String.fromCodePoint(0x2014)),
  'HTML, frontmatter, README, and verifier scanned'
);

if (failures.length) {
  console.error(`\n${failures.length} of ${reportCount} checks failed.`);
  for (const failure of failures) console.error(`  - ${failure}`);
  process.exit(1);
}

console.log(`\n${reportCount}/${reportCount} checks pass.`);
console.log('Independent routes: beam mechanics and Darcy pore-flow mechanics.');
console.log('Published anchors: 28.4 ± 9 μs, 5.3 ± 3.5 ms, and -100 ± 14 bar.');
console.log('Poison controls: stiffness x100 and permeability x100 were both rejected.');
