#!/usr/bin/env node
// verify.mjs — the offline check for "Between Zhou and the Butterfly".
//
// The house rule: every factual claim is checked and the check is shown.
// This script re-reads the three verbatim source files in this directory and
// checks selected Chinese fragments and character membership, the full English
// translations after stripping markup and normalizing whitespace, the presence
// of both renderings of 物化, and the apparatus notes. It also compares the
// ordered interlinear character list with the Chinese source.
//
// Run: node research/zhuangzi-butterfly/verify.mjs   (exit 0 = all pass)

import { readFileSync } from 'node:fs';

const HERE = new URL('.', import.meta.url).pathname;
const PAGE = readFileSync(HERE + '../../public/strata/between-zhou-and-the-butterfly/index.html', 'utf8');
const rd = (f) => readFileSync(HERE + f, 'utf8').trim();

const ORIG  = rd('original-ctext-qiwulun.txt');
const LEGGE = rd('legge-1891-sbe39.txt');
const GILES = rd('giles-1889-gutenberg59709.txt');

let pass = 0, fail = 0;
const ok  = (m) => { pass++; console.log('  ✓ ' + m); };
const bad = (m) => { fail++; console.log('  ✗ ' + m); };

// Strip HTML tags so verbatim prose on the page can be matched against the
// plain source text (the page wraps a few phrases in <mark>/<b> for emphasis).
const strip = (s) => s.replace(/<[^>]+>/g, '').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
const pagePlain = strip(PAGE);

console.log('\n1. The original Chinese: character membership and selected fragments');
{
  const han = [...ORIG].filter((c) => c >= '一' && c <= '鿿');
  // every character of the original must appear on the page
  const missing = han.filter((c) => !PAGE.includes(c));
  if (missing.length === 0) ok(`each distinct source Han character occurs somewhere on the page`);
  else bad(`missing hanzi: ${missing.join('')}`);
  // the closing line and the opening must appear as contiguous strings
  for (const frag of ['昔者莊周夢為胡蝶', '此之謂物化', '周與胡蝶，則必有分矣']) {
    if (PAGE.includes(frag)) ok(`contiguous: ${frag}`); else bad(`NOT contiguous on page: ${frag}`);
  }
}

console.log('\n2. The two full translations, after markup and whitespace normalization');
for (const [who, text] of [['Legge 1891 (SBE 39)', LEGGE], ['Giles 1889 (Gutenberg 59709)', GILES]]) {
  if (pagePlain.includes(strip(text))) ok(`${who} matches after normalization (${text.length} source chars)`);
  else {
    bad(`${who} does NOT match the normalized source`);
    // show first divergence to aid repair
    const a = strip(text), b = pagePlain;
    let i = 0; while (i < a.length && b.includes(a.slice(0, i + 1))) i++;
    console.log('      first divergence near: …' + a.slice(Math.max(0, i - 30), i + 30) + '…');
  }
}

console.log('\n3. The crux 物化 — both renderings present and attributed');
for (const phrase of ['the Transformation of Things', 'Metempsychosis']) {
  if (PAGE.includes(phrase)) ok(`crux rendering present: "${phrase}"`); else bad(`crux rendering MISSING: "${phrase}"`);
}
// the literal gloss of each character
for (const [g, label] of [['物', 'wù'], ['化', 'huà']]) {
  if (PAGE.includes(g) && PAGE.includes(label)) ok(`literal gloss anchored: ${g} (${label})`); else bad(`gloss missing for ${g}`);
}

console.log('\n4. The sourced facts are stated (not silently asserted)');
const facts = [
  ['Guo Xiang 52→33 reduction', /52 chapters to 33|52 chapters? to 33/i],
  ['Inner Chapters 1–7', /Inner Chapters/],
  ['Guo Xiang death date', /312\s*CE/],
  ['late 4th century BC dating', /4th century BC|fourth century/i],
  ['SEP cited', /plato\.stanford\.edu\/entries\/zhuangzi/],
  ['ctext cited', /ctext\.org\/zhuangzi/],
  ['Gutenberg 59709 cited', /gutenberg\.org\/ebooks\/59709/],
];
for (const [name, re] of facts) (re.test(PAGE) ? ok : bad)(name);

console.log('\n5. The honest edges are named in the apparatus');
const edges = [
  ['Legge reconciliation (dropped period) disclosed', /ISTA drops a period after .enjoying itself./i],
  ['胡蝶 vs 蝴蝶 graph noted', /蝴蝶/],
  ['glosses marked editorial', /editorial crib/i],
  ['Watson/Graham short quotations disclosed', /readings attributed to Watson and Graham[^<]*<strong>briefly quoted<\/strong>/i],
  ['title parsing ambiguity named', /齊物.*論|equalizing/i],
];
for (const [name, re] of edges) (re.test(PAGE) ? ok : bad)(name);

console.log('\n6. The interlinear data matches the original');
{
  const m = PAGE.match(/const IL = (\[.*?\]);/s);
  if (!m) bad('could not find embedded interlinear data');
  else {
    // pull the chars out of the JS array literal in document order
    const chars = [...m[1].matchAll(/c:"(.)"/g)].map((x) => x[1]).join('');
    const han = [...ORIG].filter((c) => c >= '一' && c <= '鿿').join('');
    if (chars === han) ok(`interlinear reproduces all ${han.length} characters in order`);
    else bad(`interlinear/original mismatch:\n      IL:   ${chars}\n      orig: ${han}`);
  }
}

console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${pass} checks passed, ${fail} failed.\n`);
process.exit(fail === 0 ? 0 : 1);
