#!/usr/bin/env node
/**
 * How to Freeze a River — offline claims-parity verifier (zero network).
 *
 * The portal combines four member strata. Its honesty contract: every quoted
 * string on the portal is byte-identical (modulo markup and quote-glyph style)
 * to the same string on the member page or in the member's committed ground
 * truth — so the portal cannot drift from what its members verified. Plus the
 * portal's own arithmetic (word counts, character diffs, chronology) is
 * recomputed here from the strings themselves.
 *
 * Run: node research/how-to-freeze-a-river/verify.mjs
 */
import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const root = join(here, '..', '..');

let pass = 0, fail = 0;
const ok = (cond, msg) => {
  if (cond) { pass++; console.log(`  ✓ ${msg}`); }
  else { fail++; process.exitCode = 1; console.log(`  ✗ FAIL: ${msg}`); }
};

// ---------- load everything ----------
const gt = JSON.parse(readFileSync(join(here, 'ground-truth.json'), 'utf8'));
const portalHtml = readFileSync(join(root, 'public/strata/how-to-freeze-a-river/index.html'), 'utf8');
const stub = readFileSync(join(root, 'src/content/strata/how-to-freeze-a-river.md'), 'utf8');
const river = readFileSync(join(root, 'public/strata/the-river-that-stays/index.html'), 'utf8');
const way = readFileSync(join(root, 'public/strata/the-way-that-can-be-told/index.html'), 'utf8');
const butterfly = readFileSync(join(root, 'public/strata/between-zhou-and-the-butterfly/index.html'), 'utf8');
const rheomodeGt = JSON.parse(readFileSync(join(root, 'research/rheomode/ground-truth.json'), 'utf8'));

// Text-normalize: strip tags, unify quote glyphs and whitespace. Quote-mark
// style is typography, not a factual claim; everything else must match exactly.
const norm = (s) => s
  .replace(/<[^>]*>/g, '')
  .replace(/&#x27;|&#8217;|&amp;/g, (m) => ({ '&#x27;': "'", '&#8217;': "'", '&amp;': '&' }[m]))
  .replace(/[‘’“”'"]/g, "'")
  .replace(/\s+/g, ' ')
  .trim();
const portalText = norm(portalHtml);
const riverText = norm(river);
const wayText = norm(way);
const butterflyText = norm(butterfly);
const has = (hay, needle) => norm(hay).includes(norm(needle));

// The page's embedded data island (what the instruments actually render).
const island = JSON.parse(portalHtml.match(/<script type="application\/json" id="gt">\s*([\s\S]*?)\s*<\/script>/)[1]);

const words = (s) => s.replace(/[…,."'“”]/g, ' ').trim().split(/\s+/).length;

console.log('\nHow to Freeze a River — offline verification\n');

// ---------- 1. The Greek chain: portal ↔ ground truth ↔ river member page ----------
console.log('— Demonstration I: the Greek chain —');
const b12 = gt.heraclitus.b12.greek;
ok(island.stages[0].text === b12, 'stage 1 text is B12, byte-identical to ground truth');
ok(riverText.includes(b12), 'B12 Greek appears byte-identical on the river member page');
ok(words(b12) === gt.heraclitus.b12.greek_word_count && words(b12) === 9,
  `B12 recounted: ${words(b12)} Greek words (ground truth says ${gt.heraclitus.b12.greek_word_count})`);
ok(!/δὶς|δίς/.test(b12), 'B12 contains no "twice" (δίς) — recomputed by regex');
ok(b12.includes('αὐτοῖσιν'), 'B12 contains αὐτοῖσιν, "the same" — the load-bearing word');
ok(b12.endsWith('ἐπιρρεῖ'), 'B12 ends on ἐπιρρεῖ — the flow-verb the portal\'s bridge hangs on');

const crat = gt.heraclitus.cratylus.greek;
ok(island.stages[1].text === crat, 'stage 2 text is the Cratylus paraphrase, byte-identical to ground truth');
ok(riverText.includes(crat), 'Cratylus Greek appears byte-identical on the river member page');
ok(words(crat) === 5, `Cratylus paraphrase recounted: ${words(crat)} words`);
ok(crat.includes('χωρεῖ') && !crat.includes('ῥεῖ '), 'Plato\'s verb is χωρεῖ, not ῥεῖ — recomputed');

const b91 = gt.heraclitus.b91.greek;
ok(island.stages[2].text === b91, 'stage 3 text is B91, byte-identical to ground truth');
ok(riverText.includes(b91), 'B91 Greek appears byte-identical on the river member page');
ok(words(b91) === 8, `B91 recounted: ${words(b91)} words`);
ok(/δὶς/.test(b91), 'B91 contains δίς, "twice" — the word that entered the record late');

const slogan = gt.heraclitus.panta_rhei.greek;
ok(island.stages[3].text === slogan, 'stage 4 text is πάντα ῥεῖ, byte-identical to ground truth');
ok(riverText.includes(slogan), 'πάντα ῥεῖ appears on the river member page (as a late formula, per its apparatus)');
ok(words(slogan) === 2, `the slogan recounted: ${words(slogan)} words`);
ok(!b12.includes(slogan), 'πάντα ῥεῖ is not a substring of B12 — the slogan is not in the fragment');
ok(has(portalHtml, 'locus unconfirmed'), 'the Simplicius hedge is on the portal page (inherited from the river page)');

// The compression arc, recomputed end to end.
ok(words(b12) > words(crat) && words(crat) > words(slogan),
  `compression arc recomputed: ${words(b12)} → ${words(crat)} → ${words(slogan)} words`);

// Chronology strictly increases across the five stages.
const yrs = ['b12', 'cratylus', 'b91', 'slogan', 'bohm'].map((k) => gt.heraclitus.chronology_years_after[k]);
ok(yrs.every((y, i) => i === 0 || y > yrs[i - 1]),
  `chronology strictly increases: ${yrs.join(' → ')} years after Heraclitus`);
ok(island.stages.length === 5, 'the freezer has exactly 5 stages');

// ---------- 2. Bohm: the newest layer + the rheomode, against the member's ground truth ----------
console.log('— Demonstration IV + the newest layer: Bohm —');
const bohmQ = gt.heraclitus.bohm_layer.quote;
ok(has(portalHtml, bohmQ), 'Bohm\'s p. 61 Heraclitus sentence appears verbatim on the portal');
ok(norm(bohmQ).includes(norm(island.stages[4].text.replace(/^…/, ''))),
  'stage 5 excerpt is a verbatim substring of the p. 61 sentence');
ok(norm(bohmQ).includes("everything flows"), 'p. 61 sentence contains "everything flows" — the slogan, received');

const framing = rheomodeGt.framing;
const q37 = framing.find((f) => f.pin === 'p. 37');
const q39 = framing.find((f) => f.pin === 'p. 39');
const q60 = framing.find((f) => f.pin.startsWith('p. 60'));
ok(!!q37 && has(portalHtml, q37.q), 'the p. 37 framing question matches research/rheomode/ground-truth.json verbatim');
ok(!!q39 && has(portalHtml, q39.q), 'the p. 39 rheo-etymology gloss matches research/rheomode/ground-truth.json verbatim');
ok(!!q60 && has(portalHtml, q60.q), 'the p. 60 closing non-verdict matches research/rheomode/ground-truth.json verbatim');
ok(gt.bohm.published_forms === 44 && rheomodeGt.published.length === 44,
  `44 published forms: portal ground truth agrees with the member's (${rheomodeGt.published.length} entries)`);
const casc = gt.bohm.cascade;
ok(has(portalHtml, casc.root) && has(portalHtml, casc.derived) && has(portalHtml, casc.modern),
  'the cascade levate → re-levate → relevant is on the page');
ok(rheomodeGt.etymologies.some((e) => /relev/i.test(e.word || '') || /relevare/.test(JSON.stringify(e))),
  'relevare etymology is banked in the member\'s ground truth');
// The bridge is claimed as ours, with the surface fact checkable in the letters:
ok('ἐπιρρεῖ'.normalize('NFD').includes('ρει'.normalize('NFD').replace(/̓|̔/g, '')) || 'ἐπιρρεῖ'.endsWith('ρρεῖ'),
  'surface check: ἐπιρρεῖ ends in -ρρεῖ — the ῥέω stem is present in the letters');
ok(has(portalHtml, 'the line is ours'), 'the ῥέω bridge is claimed as ours on the page, not as Bohm\'s');
ok(!has(portalHtml, 'Bohm built the rheomode on Heraclitus'), 'forbidden claim absent: Bohm built on Heraclitus');

// ---------- 3. Laozi: the taboo swap, against the way member page ----------
console.log('— Demonstration II: the taboo swap —');
const rec = gt.laozi.received, mwd = gt.laozi.mawangdui;
ok(wayText.includes(rec), 'received line 道可道，非常道 appears byte-identical on the way member page');
ok(wayText.includes(mwd), 'Mawangdui line 道可道也，非恆道也 appears byte-identical on the way member page');
ok(norm(island.laozi[1].hanzi) === norm(rec) && norm(island.laozi[0].hanzi) === norm(mwd),
  'both toggle states render exactly the ground-truth lines (markup stripped)');
const recSet = new Set(rec), mwdSet = new Set(mwd);
const onlyRec = [...recSet].filter((c) => !mwdSet.has(c)).join('');
const onlyMwd = [...mwdSet].filter((c) => !recSet.has(c)).join('');
ok(onlyRec === '常' && onlyMwd === '也恆',
  `character diff recomputed: received-only {${onlyRec}} vs Mawangdui-only {${onlyMwd}} — exactly the taboo swap plus the 也 particles`);
ok(has(portalHtml, '劉恆') && has(portalHtml, 'Liu Heng'), 'the emperor is named (劉恆 / Liu Heng) with the taboo mechanism');
ok(wayText.includes('劉恆') || wayText.includes('Liú Héng') || wayText.includes('Liu Heng'),
  'the member page carries the same taboo attribution');
ok(has(portalHtml, 'do not contain this chapter'), 'the Guodian caveat is stated (the slips do NOT contain ch. 1)');
ok(has(portalHtml, 'tomb sealed 168 BCE'), 'the Mawangdui tomb date (168 BCE) is stated');

// ---------- 4. Zhuangzi: the tense trap, against the butterfly member page ----------
console.log('— Demonstration III: the tense trap —');
ok(butterflyText.includes(norm(gt.zhuangzi.mirror_pair)), 'the mirror pair appears byte-identical on the butterfly member page');
ok(butterflyText.includes(norm(gt.zhuangzi.closing)), 'the closing line 此之謂物化 appears byte-identical on the butterfly member page');
ok(has(portalHtml, '周之夢為胡蝶與') && has(portalHtml, '胡蝶之夢為周與'),
  'both halves of the mirror pair are on the portal');
ok(butterflyText.includes(norm(gt.zhuangzi.giles_clause)), 'Giles\'s clause matches the butterfly page byte-for-byte (markup stripped)');
ok(butterflyText.includes(norm(gt.zhuangzi.legge_clause)), 'Legge\'s clause matches the butterfly page byte-for-byte (markup stripped)');
ok(has(portalHtml, gt.zhuangzi.giles_clause), 'Giles\'s clause is quoted on the portal');
ok(has(portalHtml, gt.zhuangzi.legge_clause), 'Legge\'s clause is quoted on the portal');
ok(has(portalHtml, 'the Transformation of Things') && has(portalHtml, 'Metempsychosis'),
  'both destinies of 物化 (Legge/Watson vs Giles) are shown');
ok(butterflyText.includes('the Transformation of Things') && butterflyText.includes('Metempsychosis'),
  'and both appear on the member page the same way');
ok(!/物化\s*means\s*metempsychosis/i.test(portalText), 'forbidden claim absent: 物化 = metempsychosis asserted as fact');

// ---------- 5. The spine: every link resolves ----------
console.log('— The spine: links and stubs —');
for (const m of gt.meta.members) {
  ok(portalHtml.includes(`href="${m.url}"`), `portal links to ${m.url}`);
  ok(existsSync(join(root, 'src/content/strata', `${m.slug}.md`)), `member stub exists: ${m.slug}.md`);
  ok(existsSync(join(root, 'public/strata', m.slug, 'index.html')), `member page exists: /strata/${m.slug}/`);
}
for (const slug of ['old-pond', 'the-empty-mountain', 'zero-years-deep']) {
  ok(portalHtml.includes(`/strata/${slug}/`) && existsSync(join(root, 'src/content/strata', `${slug}.md`)),
    `adjacent link resolves: ${slug}`);
}
ok(portalHtml.includes('/strata/deposition/'), 'the falsifier invitation points at the door');
ok(/tags:.*"portal".*"combine"/.test(stub), 'stub is tagged portal + combine');
ok(stub.includes('href: "/strata/how-to-freeze-a-river/"'), 'stub href matches the page');
for (const m of gt.meta.members) {
  ok(new RegExp(`- to: ${m.slug}`).test(stub), `stub declares a relates: edge to ${m.slug}`);
}

// ---------- 6. Guardrails and independence ----------
console.log('— Guardrails —');
ok(has(portalHtml, 'no known contact'), 'independence stated as "no known contact" (typological, not genetic)');
ok(has(portalHtml, 'Not that grammar imprisons thought'), 'the Whorf guardrail paragraph is present');
ok(has(portalHtml, 'refuted by Malotki'), 'Malotki correction named on the portal');
ok(has(portalHtml, 'argued, not settled') || has(portalHtml, 'argument, and it is argued'),
  'the Kirk persistence-reading is framed as an argument with dissent, not settled fact');
ok(has(portalHtml, 'Four cases, documented') || has(portalHtml, 'four cases, documented'),
  'the pattern is bounded to four documented cases, not claimed as a law');

// ---------- 7. Claims parity: the tally the page displays ----------
console.log('— Tally parity —');
const total = pass + fail + 1; // +1 = this very check
const tallyMatch = portalHtml.match(/id="checkTally">([^<]*)</);
ok(!!tallyMatch && tallyMatch[1].trim() === String(total),
  `the page's printed tally (${tallyMatch ? tallyMatch[1].trim() : 'missing'}) equals the recomputed check count (${total})`);

console.log(`\n${pass}/${pass + fail} checks passed${fail ? ` — ${fail} FAILED` : ''}\n`);
