#!/usr/bin/env node
// The Act Alone: scoped quotation and structure checks, 2026-10-01.
// Run: node research/the-act-alone/verify.mjs
// This reads the authored HTML. It does not build the page or run on page load.
// Source transcription repairs are explicit in quotation-check.mjs.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { parse } from 'parse5';
import { witnesses, normalise, checkQuotations } from '../../public/strata/the-act-alone/quotation-check.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PAGE = path.join(HERE, '../../public/strata/the-act-alone/index.html');
const attr = (n, name) => n.attrs?.find(a => a.name === name)?.value;
const hasClass = (n, name) => (attr(n, 'class') || '').split(/\s+/).includes(name);
function descendants(node) {
  return [node, ...(node.childNodes || []).flatMap(descendants)];
}
function quoteText(node) {
  if (['script', 'style'].includes(node.tagName) || hasClass(node, 'src') || hasClass(node, 'who')) return '';
  if (node.nodeName === '#text') return node.value;
  return (node.childNodes || []).map(quoteText).join('');
}
function text(node) {
  if (['script', 'style'].includes(node.tagName)) return '';
  if (node.nodeName === '#text') return node.value;
  return (node.childNodes || []).map(text).join('');
}

export function verifyPage(html) {
  const nodes = descendants(parse(html));
  const results = checkQuotations(id => {
    const matches = nodes.filter(n => attr(n, 'id') === id);
    return matches.length === 1 ? quoteText(matches[0]) : null;
  });
  const add = (label, ok) => results.push({ label, ok });
  const gallery = nodes.find(n => hasClass(n, 'gallery'));
  const rows = gallery ? descendants(gallery).filter(n => hasClass(n, 'row')) : [];
  add('Gallery has eight selected versions', rows.length === 8);
  const words = rows.map(n => descendants(n).find(c => hasClass(c, 'adhi-rendering'))).map(n => n ? text(n) : '');
  add('Five distinct gallery headwords', new Set(words).size === 5 && words.every(Boolean));
  const parser = nodes.find(n => hasClass(n, 'parser-grid'));
  const children = parser?.childNodes.filter(n => n.tagName) || [];
  const cells = children.filter(n => hasClass(n, 'cell'));
  add('Parser has 32 cells', cells.length === 32);
  const arnold = children.findIndex(n => hasClass(n, 'pname') && text(n).includes('Arnold'));
  add('Arnold clause 4 is reframed as a positive imperative', arnold >= 0 &&
    hasClass(children[arnold + 4], 'reframed') && text(children[arnold + 4]).includes('REFRAMED ④'));
  add('Seven merged cells; no omitted clause', cells.filter(n => hasClass(n, 'merged')).length === 7 &&
    cells.filter(n => hasClass(n, 'dropped')).length === 0);
  const strata = nodes.find(n => hasClass(n, 'strata'));
  const layers = strata ? descendants(strata).filter(n => hasClass(n, 'layer')) : [];
  add('Transmission stratigraphy has 13 layers', layers.length === 13);
  const firstWhat = layers[0] && descendants(layers[0]).find(n => hasClass(n, 'what'));
  add('Opening transmission node gives 32 syllables', !!firstWhat && /\b32 syllables\b/.test(text(firstWhat)));
  return results;
}

export function verifySources(read = file => readFileSync(path.join(HERE, file), 'utf8')) {
  return witnesses.map(w => {
    const source = read(w.file).replace(/\s+/g, ' ').trim();
    let repaired = w.raw;
    let repairsPresent = true;
    for (const [from, to] of w.repairs) {
      if (!repaired.includes(from)) repairsPresent = false;
      repaired = repaired.replaceAll(from, to);
    }
    return { label: `Source and recorded repairs: ${w.label}`,
      ok: source.includes(w.raw) && repairsPresent && normalise(repaired, w.mode) === normalise(w.text, w.mode) };
  });
}

if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
  const results = [...verifySources(), ...verifyPage(readFileSync(PAGE, 'utf8'))];
  for (const r of results) console.log(`${r.ok ? 'PASS' : 'FAIL'} ${r.label}`);
  const failed = results.filter(r => !r.ok).length;
  console.log(`\n${results.length - failed}/${results.length} PASS; ${failed} fail.`);
  console.log('Scope: gallery quotations, two pull-quotes, two complete Sanskrit displays, and the named structure checks. Other prose and media are not verified.');
  process.exitCode = failed ? 1 : 0;
}
