// research/the-ink-that-eats-its-words/verify.mjs
// Offline verifier for /strata/the-ink-that-eats-its-words/.
// Recomputes every number the page displays (Sebera's published isoperm values,
// the Tétreault 2023 benchmark multipliers, the Barrow fold-endurance series)
// from constants.json, and byte-checks (whitespace-normalized) that the page
// shows exactly the sourced claims recorded in sources.json.
// Run: node research/the-ink-that-eats-its-words/verify.mjs
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const PAGE = readFileSync(join(ROOT, 'public/strata/the-ink-that-eats-its-words/index.html'), 'utf8');
const MD = readFileSync(join(ROOT, 'src/content/strata/the-ink-that-eats-its-words.md'), 'utf8');
const C = JSON.parse(readFileSync(join(HERE, 'constants.json'), 'utf8'));
const SOURCES = JSON.parse(readFileSync(join(HERE, 'sources.json'), 'utf8'));

const norm = (s) => s.replace(/\s+/g, ' ');
const PAGE_N = norm(PAGE);

let pass = 0, fail = 0;
const bad = [];
function check(name, ok, detail) {
  if (ok) { pass++; }
  else { fail++; bad.push(name + (detail ? ' — ' + detail : '')); }
}
function pageHas(name, needle) {
  check(name, PAGE_N.includes(norm(needle)), 'page missing: ' + JSON.stringify(String(needle).slice(0, 90)));
}

/* ── 0 · structural honesty ───────────────────────────────────────────── */
check('no unfilled scaffold markers shipped', !PAGE.includes('⟦FILL') && !PAGE.includes('FILL:'), 'a scaffold slot survived to production');
check('markdown has no scaffold markers', !MD.includes('⟦FILL'));
check('page carries canonical URL', PAGE.includes('https://artwaste.land/strata/the-ink-that-eats-its-words/'));
check('page carries the way-out footer', PAGE.includes('aw-wayout') && PAGE.includes('/archive/'));
check('page carries home-banner include', PAGE.includes('/media/home-banner.js'));
check('page closes its script/body/html', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(PAGE.trim()));

/* ── 1 · the vault: Sebera isoperm, recomputed ───────────────────────────
   Isoperm (Sebera 1994, CPA/CLIR; conventional Arrhenius form, validated
   below against his own published diagram values):
   P2/P1 = (RH1/RH2) · exp[(Ea/R)(1/T2 − 1/T1)], T in kelvin.               */
const R = 8.314462618; // J/(mol·K)
function isoperm(EaKJ, T1c, RH1, T2c, RH2) {
  const T1 = T1c + 273.15, T2 = T2c + 273.15;
  return (RH1 / RH2) * Math.exp(((EaKJ * 1000) / R) * (1 / T2 - 1 / T1));
}

// 1a. the MODEL block in the page must carry exactly the constants of record
for (const key of ['EA_KJMOL_LOW', 'EA_KJMOL_MID', 'EA_KJMOL_HIGH']) {
  const m = PAGE.match(new RegExp(key + ':\\s*([0-9.]+)'));
  check(`page MODEL.${key} = ${C.isoperm[key]}`, m && Number(m[1]) === C.isoperm[key], m ? `page has ${m[1]}` : 'not found');
}
for (const [key, want] of [['BASE_T_C', C.isoperm.BASE_T_C], ['BASE_RH', C.isoperm.BASE_RH]]) {
  const m = PAGE.match(new RegExp(key + ':\\s*([0-9.]+)'));
  check(`page MODEL.${key} = ${want}`, m && Number(m[1]) === want, m ? `page has ${m[1]}` : 'not found');
}

// 1b. the page's isoperm function is FUNCTIONALLY IDENTICAL to this one
{
  const m = PAGE.match(/function isoperm\(EaKJ, T1c, RH1, T2c, RH2\) \{[\s\S]*?\n    \}/);
  check('page defines the canonical isoperm function', Boolean(m));
  if (m) {
    const pageIso = new Function('return ' + m[0])();
    let worst = 0;
    for (const ea of [95, 110, 130, 146.44])
      for (const t of [0, 12.2222, 20, 25.5556, 35])
        for (const rh of [30, 50, 65, 80]) {
          const a = isoperm(ea, 20, 50, t, rh), b = pageIso(ea, 20, 50, t, rh);
          worst = Math.max(worst, Math.abs(a - b) / a);
        }
    check('page isoperm ≡ verifier isoperm (80-point grid)', worst < 1e-12, 'max rel diff ' + worst);
  }
}

// 1c. recompute Sebera's own published isoperm-diagram values
for (const s of C.isoperm.sebera_published) {
  const got = isoperm(s.ea_kjmol, s.from_t_c, s.from_rh, s.to_t_c, s.to_rh);
  const ok = Math.abs(got - s.published) / s.published < s.tol;
  check(`Sebera published ${s.label} = ${s.published}`, ok, `recomputed ${got.toPrecision(4)}`);
  if (s.shown_as) pageHas(`page shows Sebera ${s.published}`, s.shown_as);
}

// 1d. recompute the Tétreault 2023 benchmark multipliers
for (const s of C.isoperm.tetreault_benchmarks) {
  const got = isoperm(s.ea_kjmol, s.from_t_c, s.from_rh, s.to_t_c, s.to_rh);
  const ok = Math.abs(got - s.published) / s.published < s.tol;
  check(`Tétreault ${s.label} = ×${s.published}`, ok, `recomputed ×${got.toPrecision(4)}`);
}
pageHas('page shows the Tétreault trio', '×2.0/×2.2/×2.6');

// 1e. the vault's sliders stay inside Sebera's stated RH validity band
{
  const m = PAGE.match(/id="rh" min="(\d+)" max="(\d+)"/);
  check('RH slider bounded to 30–65% (Sebera validity)', m && m[1] === '30' && m[2] === '65', m ? `${m[1]}–${m[2]}` : 'not found');
}

/* ── 2 · the valley chart data = the sourced Barrow table, exactly ─────── */
{
  const m = PAGE.match(/var DATA = (\[[\s\S]*?\]);/);
  check('valley DATA present in page', Boolean(m));
  if (m) {
    let pageData = null;
    try { pageData = JSON.parse(m[1]); } catch (e) { /* fail below */ }
    check('valley DATA parses as JSON', Boolean(pageData));
    if (pageData) {
      check('valley DATA matches Barrow transcription exactly',
        JSON.stringify(pageData) === JSON.stringify(C.valley.rows),
        'page chart data drifted from the sourced table');
      const ns = pageData.reduce((a, d) => a + d.n, 0);
      check('valley sample sizes sum to 1,470', ns === 1470, 'sum=' + ns);
      const floor = pageData.reduce((a, d) => (d.f < a.f ? d : a));
      check('the floor is 1850–1899 at 6 folds', floor.p === '1850-1899' && floor.f === 6);
    }
  }
}

/* ── 3 · every dated / numeric historical claim on the page ───────────── */
for (const cl of SOURCES.claims) {
  if (cl.must_appear) {
    for (const needle of [].concat(cl.must_appear)) pageHas(`claim ${cl.id}`, needle);
  }
  check(`claim ${cl.id} has a real source`, Boolean(cl.source && cl.source.url && cl.source.title));
  if (cl.verdict) check(`claim ${cl.id} adversarial verdict`, cl.verdict === 'CONFIRMED' || cl.verdict === 'CORRECTED', cl.verdict);
}

/* ── 4 · markdown entry consistency ────────────────────────────────────── */
check('md href points at the page', MD.includes('href: "/strata/the-ink-that-eats-its-words/"'));
check('md and page share the poetic title', MD.includes('The Ink That Eats Its Words'));
check('md carries the search-facing seoTitle', MD.includes('seoTitle:'));

/* ── report ───────────────────────────────────────────────────────────── */
console.log('\nthe-ink-that-eats-its-words · verify');
console.log(`  ${pass}/${pass + fail} checks pass`);
if (fail) { console.log('  FAILURES:'); bad.forEach(b => console.log('   ✗ ' + b)); process.exit(1); }
