// research/no-word-for-it/verify.mjs
//
// The gate for the portal "No Word for It" (public/strata/no-word-for-it/).
// Portal law: a portal BUILDS NO NEW FACT. Every figure it shows must already
// live on a member's verified page. This script makes that checkable:
//
//   §1  every chip (a verbatim rendering + attribution) in the portal's embedded
//       data appears verbatim in its member's committed page HTML
//   §2  every count the portal states is re-derived from the portal's own
//       embedded data (chips, distinct hands, doubled words, sense splits)
//   §3  the load-bearing hedges are actually present in the portal's prose
//       (the cited-not-recomputed marker, the no-ranking rule, the PD bounds)
//   §4  the static exhibits and the instrument agree: every chip string in the
//       data also appears in the page's static HTML (the no-JS reader sees the
//       same record the instrument shows)
//   §5  all SEVEN member verifiers are re-run, each required to exit 0
//   §6  page chrome: the canonical banner script, way-out footer, nearby markers
//
// Run: node research/no-word-for-it/verify.mjs        (exit 0 = all pass)

import { readFileSync, existsSync } from 'node:fs';
import { execSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const PAGE = join(ROOT, 'public', 'strata', 'no-word-for-it', 'index.html');

let checks = 0, fails = 0;
const ok = (cond, msg) => { checks++; if (cond) console.log('  ✓ ' + msg); else { fails++; console.log('  ✗ ' + msg); } };

// Normalise text for cross-file matching: strip tags, unescape the common
// entities, fold curly quotes/apostrophes to straight, collapse whitespace.
const norm = (s) => s
  .replace(/<[^>]+>/g, '')
  .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
  .replace(/&#39;|&apos;|’|‘/g, "'")
  .replace(/[“”]/g, '"')
  .replace(/\s+/g, ' ');

const pageRaw = readFileSync(PAGE, 'utf8');
const dataMatch = pageRaw.match(/<script id="wordsdata" type="application\/json">([\s\S]*?)<\/script>/);
if (!dataMatch) { console.log('  ✗ wordsdata block missing'); process.exit(1); }
const WORDS = JSON.parse(dataMatch[1]).words;
const pageSansData = norm(pageRaw.replace(dataMatch[0], ''));

const memberHtml = {};
for (const w of WORDS) {
  const p = join(ROOT, 'public', 'strata', w.member, 'index.html');
  memberHtml[w.member] = norm(readFileSync(p, 'utf8'));
}

console.log('no-word-for-it — portal verification\n');

// ── §1 every chip is verbatim on its member's committed page ──
console.log('§1  chip provenance (verbatim against the member pages)');
for (const w of WORDS) {
  const m = memberHtml[w.member];
  for (const c of w.chips) {
    if (c.ghost) {
      // the greyed "named, not shown" chip: its names must appear in member prose
      const names = c.t.split('·').map(s => s.trim());
      ok(names.every(n => m.includes(n)), `${w.id}: ghost chip names (${c.t}) named in ${w.member}`);
    } else {
      ok(m.includes(norm(c.t)), `${w.id}: "${c.t}" verbatim in ${w.member}`);
    }
  }
}

// ── §2 every stated count re-derived from the data ──
console.log('\n§2  counts re-derived from the embedded data');
{
  const ex = WORDS.find(w => w.id === 'excrucior');
  const hands = new Set(ex.chips.map(c => c.att.split(/\s|·/)[0]));
  ok(ex.chips.length === 10 && ex.counts.chips === 10, `excrucior: 10 renderings (data has ${ex.chips.length})`);
  ok(hands.size === 9 && ex.counts.hands === 9, `excrucior: 9 distinct hands (data has ${hands.size})`);
  ok(ex.chips.filter(c => c.mark).length === 1, 'excrucior: exactly 1 marked passive-keeper (Kelly)');

  const an = WORDS.find(w => w.id === 'antan');
  ok(an.chips.filter(c => !c.ghost).length === 2 && an.counts.chips === 2, 'antan: 2 shown poles');

  const ad = WORDS.find(w => w.id === 'adhikara');
  const texts = ad.chips.map(c => c.t);
  const distinct = new Set(texts);
  const doubled = [...distinct].filter(t => texts.filter(x => x === t).length > 1);
  ok(ad.chips.length === 8, 'adhikāra: 8 versions');
  ok(distinct.size === 5 && ad.counts.distinct === 5, `adhikāra: 5 distinct words (data has ${distinct.size})`);
  ok(doubled.length === 2 && ad.counts.doubled === 2, `adhikāra: 2 doubled (${doubled.join(', ')})`);

  const he = WORDS.find(w => w.id === 'hesed');
  const senseII = he.chips.filter(c => c.src).length;
  ok(he.chips.length === 11 && he.counts.chips === 11, 'ḥesed: 11 shown renderings');
  ok(senseII === 2 && he.chips.length - senseII === 9, `ḥesed: 9 sense I + 2 sense II (homonym)`);

  const re = WORDS.find(w => w.id === 'ren');
  const legge = re.chips.filter(c => c.att.startsWith('Legge'));
  ok(legge.length === 6 && new Set(legge.map(c => c.t)).size === 6, '仁: Legge 6 distinct renderings in one book');
  ok(re.chips.filter(c => c.att.startsWith('Lyall')).length === 1, '仁: Lyall count of one');

  const ma = WORDS.find(w => w.id === 'malik');
  ok(ma.chips.length === 4, 'mālik: 4 versions');
  ok(ma.chips.filter(c => !c.src).length === 2 && ma.chips.filter(c => c.src).length === 2, 'mālik: 2 King vs 2 Master/Owner');
  ok(ma.chips.filter(c => !c.src).every(c => c.att.includes('malik')) &&
     ma.chips.filter(c => c.src).every(c => c.att.includes('mālik')), 'mālik: split follows the two canonical readings');

  const ep = WORDS.find(w => w.id === 'epiousios');
  ok(ep.chips.length === 5, 'epiousios: 5 Bibles');
  ok(ep.chips.filter(c => c.src).length === 2 && ep.chips.filter(c => !c.src).length === 3, 'epiousios: 2 substance vs 3 daily');
  ok(ep.chips.filter(c => c.src).every(c => c.att.includes('Vulgate')), 'epiousios: both substance readings from the Vulgate');
}

// ── §3 the load-bearing hedges are present in the portal prose ──
console.log('\n§3  hedges present in the prose (the honesty is on the page, not just here)');
for (const [needle, why] of [
  ['about a dozen', 'the ḥesed page\'s own "about a dozen" carried beside the 11'],
  ['did not recompute', 'the ~87% Septuagint figure marked cited-not-recomputed'],
  ['213 of', 'the cited count\'s own numerator/denominator shown'],
  ['never sorted', 'the no-ranking rule stated for the instrument'],
  ['one fan at a time', 'the no-shared-axis rule stated'],
  ['300', 'the Gītā corpus PD-bound (8 of 300+) stated'],
  ['cannot toggle', 'the upstream-fork quote from the-seven-doubled carried'],
  ['belongs to the translator, not the word', 'the one added sentence, stated as the portal\'s own'],
  ['not an experiment', 'the curated-gallery-not-a-sample hedge'],
  ['in copyright', 'the copyright boundary of the Villon corpus named'],
]) ok(pageSansData.toLowerCase().includes(needle.toLowerCase()), why);

// ── §4 static exhibits and instrument agree ──
console.log('\n§4  static exhibits carry the same chips as the instrument data');
for (const w of WORDS) {
  const missing = w.chips.filter(c => !c.ghost && !pageSansData.includes(norm(c.t)));
  ok(missing.length === 0, `${w.id}: all ${w.chips.filter(c => !c.ghost).length} chips also in static HTML${missing.length ? ' (missing: ' + missing.map(c => c.t).join('; ') + ')' : ''}`);
}

// ── §5 re-run all seven member verifiers ──
console.log('\n§5  the member verifiers, re-run fresh (each must exit 0)');
const MEMBER_VERIFIERS = [
  ['odi-et-amo', 'research/catullus-85/verify.mjs'],
  ['the-snows-of-yesteryear', 'research/villon-antan/verify.mjs'],
  ['the-act-alone', 'research/the-act-alone/verify.mjs'],
  ['the-word-for-both', 'research/chesed/verify.mjs'],
  ['for-want-of-a-better-term', 'research/analects-ren/verify.mjs'],
  ['the-seven-doubled', 'research/the-seven-doubled/verify.mjs'],
  ['the-bread-with-no-name', 'research/the-bread-with-no-name/verify.mjs'],
];
for (const [member, rel] of MEMBER_VERIFIERS) {
  const p = join(ROOT, rel);
  if (!existsSync(p)) { ok(false, `${member}: verifier ${rel} MISSING`); continue; }
  let passed = true, tail = '';
  try {
    const out = execSync(`node ${JSON.stringify(p)}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 300000 });
    tail = out.trim().split('\n').pop();
  } catch (e) {
    passed = false;
    tail = ((e.stdout || '') + (e.stderr || '')).trim().split('\n').slice(-2).join(' | ');
  }
  ok(passed, `${member}: ${rel} → ${tail}`);
}

// ── §6 page chrome (the design-system law) ──
console.log('\n§6  chrome');
ok(pageRaw.includes('src="/media/home-banner.js"'), 'canonical top-bar script present');
ok(pageRaw.includes('class="aw-wayout"'), 'canonical way-out footer present');
ok(pageRaw.includes('<!--aw-nearby-->'), 'nearby-layers markers present');
ok(pageRaw.includes('rel="canonical"'), 'canonical URL set');

console.log(`\n${fails === 0 ? 'ALL PASSED' : 'FAILURES'} — ${checks - fails}/${checks} checks`);
process.exit(fails === 0 ? 0 : 1);
