#!/usr/bin/env node
/* Headless-browser check for /strata/abandon-all-hope/ (The Gate Built by Love).
   Serves public/ statically, drives the page: instruments render, toggles toggle,
   hands open, career variants switch, counts are computed, no JS errors, no
   horizontal overflow at 390/768/1440. Run: node verify-abandon-all-hope.mjs */
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { existsSync, statSync } from 'node:fs';
import { join, extname } from 'node:path';
import pkg from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pkg;

const ROOT = new URL('.', import.meta.url).pathname;
const T = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png' };
const server = http.createServer(async (req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  const fp = join(ROOT, 'public', p);
  if (!existsSync(fp) || !statSync(fp).isFile()) { res.writeHead(404); res.end('nf'); return; }
  res.writeHead(200, { 'content-type': T[extname(fp)] || 'application/octet-stream' });
  res.end(await readFile(fp));
});
await new Promise(r => server.listen(0, r));
const base = 'http://localhost:' + server.address().port;

const browser = await chromium.launch();
const errors = [];
let pass = 0, fail = 0;
const ok = (cond, label) => { if (cond) { pass++; } else { fail++; console.error('  ✗ ' + label); } };

const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('pageerror', e => errors.push(String(e.message)));
page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto(base + '/strata/abandon-all-hope/', { waitUntil: 'networkidle' });

/* instruments render */
ok(await page.locator('.gline').count() === 9, 'nine Italian lines render');
ok(await page.locator('.hand').count() === 15, 'fifteen hands render');
ok(await page.locator('.gate-toggles button').count() === 3, 'three gate toggles');
ok(await page.locator('.variants button').count() === 3, 'three career variants');
ok(await page.locator('.att').count() === 11, 'modern variant shows 11 attestations by default');

/* THE ARRANGEMENT, which counting cannot reach.
   Every assertion above this line is a count or a substring, and on 2026-08-14 the
   arrangement sweep reversed every sequence this page renders, the nine lines of the
   gate inscription among them, and this check stayed green through all 238 moved
   slots. Nine lines are nine lines in any order. On a page whose artefact is a poem
   the order IS the artefact: with the sequence reversed, LASCIATE OGNI SPERANZA is
   the first thing over the gate and PER ME SI VA the last, and nothing here objected.
   So the lines are now held to their own positions, and the ledger to its chronology.
   Record: research/verifier-independence/arrange-order-*.json. */
{
  const nums = (await page.locator('.gline__n').allInnerTexts()).map(s => s.trim());
  ok(nums.join(',') === '1,2,3,4,5,6,7,8,9', `the nine lines are numbered 1 to 9 down the page (got ${nums.join(',')})`);

  const lines = (await page.locator('.gline__it').allInnerTexts()).map(s => s.replace(/\s+/g, ' ').trim());
  ok(/^Per me si va ne la citt/.test(lines[0]), 'the first line over the gate is the first line of the inscription');
  ok(/Lasciate ogni speranza/.test(lines[8]), 'the ninth line is the one the page is named for, and it is ninth');
  ok(lines.slice(0, 3).every(l => /^per me si va/i.test(l)) && !lines.slice(3).some(l => /^per me si va/i.test(l)),
    'the anaphora is lines 1 to 3 and nowhere else');

  const years = (await page.locator('.att__yr').allInnerTexts()).map(s => parseInt(s.trim(), 10));
  ok(years.length === 11 && years.every(y => Number.isFinite(y)), 'every attestation row shows a year');
  ok(years.every((y, i) => i === 0 || years[i - 1] <= y), `the ledger runs forwards in time (got ${years.join(' ')})`);
  ok(years[0] === Math.min(...years), 'the earliest attestation is the first row, not merely present somewhere');
}

/* THE STATIC FIGURES, which nothing above reads.
   On 2026-09-25 the mutation test bumped one digit in each of the five static figures
   this page prints (a Gutenberg or archive.org identifier in the source apparatus, and
   the composition date in the header) and this check stayed green all five times. Each
   is now read from the RENDERED text and compared with a value taken from the layer's
   own committed research record, not from the page, so a drifted digit on either side
   goes red. Checked live 2026-09-26: gutenberg.org #8800 and #1005 are Cary's
   translation, #1001 is Longfellow's Hell, archive.org cu31924012408179 is Anderson's
   1921 World Book edition, and "begun c. 1308, completed c. 1321" is Wikipedia's
   Divine Comedy lead. */
{
  const RD = join(ROOT, 'research', 'dante-gate');
  const hands = JSON.parse(await readFile(join(RD, 'english-hands.json'), 'utf8'));
  const hand = (yr, who) => hands.find(h => h.year === yr && h.translator.includes(who));
  const pg = h => [...h.source.matchAll(/gutenberg #(\d+)/g)].map(m => m[1]);
  const ia = h => (h.source.match(/^archive\.org (\S+)$/) || [])[1];
  const app = (await page.locator('#app-hands').innerText()).replace(/\s+/g, ' ');

  const [cary, caryX] = pg(hand(1814, 'Cary'));
  ok(app.includes(`Cary 1814 (Gutenberg #${cary},`),
    `Cary 1814 is cited as Gutenberg #${cary}, the ebook the research record fetched`);
  ok(app.includes(`Cary 1814 (Gutenberg #${cary}, cross-checked #${caryX})`),
    `Cary's second witness is cited as #${caryX}, as in the research record`);
  const [lf] = pg(hand(1867, 'Longfellow'));
  ok(app.includes(`Longfellow 1867 (Gutenberg #${lf})`),
    `Longfellow 1867 is cited as Gutenberg #${lf}, as in the research record`);
  const and = ia(hand(1921, 'Anderson'));
  ok(and && app.includes(`Anderson 1921 (${and})`),
    `Anderson 1921 is cited as archive.org ${and}, as in the research record`);

  const wiki = await readFile(join(RD, 'sources', 'vfy-wikipedia-list-of-translations.txt'), 'utf8');
  const [, y0, y1] = wiki.match(/written between (\d{4}) and (\d{4})/) || [];
  const spec = (await page.locator('.specimen').innerText()).replace(/\s+/g, ' ');
  const want = y0 && `DANTE ALIGHIERI, C. ${y0}–${y1.slice(2)}`;
  ok(want && spec.toUpperCase().includes(want),
    `the header dates the poem c. ${y0}–${y1 && y1.slice(2)}, as the committed Wikipedia source does (got "${spec.match(/DANTE ALIGHIERI[^A-Z]*?\d+–\d+/i)?.[0]}")`);
}

/* counts computed from data */
const counts = await page.locator('#handsCount').innerText();
ok(/0 of 15/.test(counts) && /3 of 15/.test(counts) && /2 of 15/.test(counts), 'counts line computed (0/15 abandon-first, 3/15 here, 2/15 every): ' + counts.slice(0, 80));

/* interactions */
await page.locator('.gate-toggles button').nth(1).click();
ok(await page.locator('.gate.show-trin').count() === 1, 'trinity toggle applies');
ok((await page.locator('#gateRead').innerText()).includes('Trinity'), 'gate readout updates');
await page.locator('.gline').nth(8).click();
ok(await page.locator('.gline.open').count() === 1, 'line 9 opens its crib');
await page.locator('.hand__row').nth(2).click();
ok(await page.locator('.hand.open').count() === 1, 'a hand opens (Cary)');
await page.locator('.variants button').nth(1).click();
ok(await page.locator('.att').count() === 5, 'older-variant ledger shows 5 rows');
ok((await page.locator('#careerRead').innerText()).includes('1839'), 'career readout switches to 1839');
await page.locator('.variants button').nth(2).click();
ok(await page.locator('.att').count() === 5, 'Cary-lineage ledger shows 5 rows');

/* THE CLAIMS PASS OF 2026-10-11, which nothing above could see.
   The page dated the exact modern wording to 1885 (it is in print by 1848), called Cary's
   object-first order "like the Italian" (Dante's line is verb-first), dated Cary's line to
   1814 (he printed it in 1805), said "most" English hands make line 1 say "you" (five of
   the fifteen do), and quoted the 1893 Indianapolis Journal in words that are not in it.
   Every one of those passed every check above. Each is now held to the layer's own
   research record (line-career.json) or to the page's own row data. */
{
  const RD = join(ROOT, 'research', 'dante-gate');
  const career = JSON.parse(await readFile(join(RD, 'line-career.json'), 'utf8'));
  const letters = s => s.toLowerCase().replace(/[^a-z]/g, '');
  const byUrl = new Map(career.earliest_confirmed_hits.map(h => [h.url, h]));
  const ledger = async n => {
    await page.locator('.variants button').nth(n).click();
    return page.locator('.att').evaluateAll(els => els.map(el => ({
      yr: parseInt(el.querySelector('.att__yr').textContent, 10),
      url: (el.querySelector('.att__work a') || { getAttribute: () => null }).getAttribute('href'),
      ctx: el.querySelector('.att__ctx').textContent,
    })));
  };

  const modern = await ledger(0);
  const earliest = Math.min(...career.earliest_confirmed_hits
    .filter(h => /^Abandon all hope,? ye who enter here/i.test(h.phrase))
    .map(h => parseInt(h.year, 10)));
  ok(modern.length > 0 && modern[0].yr === earliest,
    `the modern ledger opens on the research record's earliest exact printing, ${earliest} (got ${modern[0] && modern[0].yr})`);
  ok((await page.locator('#careerRead').innerText()).includes(`Earliest exact printing we could confirm: ${earliest}`),
    `the modern readout dates the earliest exact printing to ${earliest}`);
  const older = await ledger(1);
  const cary = await ledger(2);
  ok(cary.length > 0 && cary[0].yr === 1805 && /critical-review/.test(cary[0].url || ''),
    `the Cary ledger opens on his 1805 printing, linked to the Critical Review scan (got ${cary[0] && cary[0].yr})`);

  /* every quoted span in a ledger row's context is in that row's recorded context quote */
  const bad = [];
  for (const r of [...modern, ...older]) {
    const h = byUrl.get(r.url);
    if (!h) { bad.push(`${r.yr}: no research record for ${r.url}`); continue; }
    for (const [, q] of r.ctx.matchAll(/“([^”]+)”/g))
      if (!letters(h.context_quote).includes(letters(q))) bad.push(`${r.yr}: “${q}”`);
  }
  ok(bad.length === 0, 'every quoted span in the two ledgers is in that row\'s recorded context quote' +
    (bad.length ? ': ' + bad.join(' | ') : ''));

  /* line 1's note counts the hands that address "you" exactly as the hand rows do */
  const fulls = await page.locator('.hand__full').allTextContents();
  const personal = fulls.filter(f => /\b(you|ye)\b/i.test(f.split(/[\n;:]/)[0])).length;
  const note1 = (await page.locator('.gline__note').first().textContent()) || '';
  const WORD = ['None', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten'];
  ok(fulls.length === 15 && note1.includes(`${WORD[personal]} of the fifteen English hands personalise it`),
    `line 1's note gives the hand rows' own count of "you" (${personal} of ${fulls.length})`);

  /* line 9 is verb-first; no sentence outside the dated Corrected note, or the claims record
     scripts/assay-fold.mjs folds in (which quotes the corrected claim word for word), calls
     Cary's object-first order the Italian's */
  const src = await readFile(join(ROOT, 'public', 'strata', 'abandon-all-hope', 'index.html'), 'utf8');
  const claims = src.replace(/<!--aw-assay:start-->[\s\S]*?<!--aw-assay:end-->/g, '')
    .replace(/<p>Corrected \d{4}-\d\d-\d\d[\s\S]*?<\/p>/g, '');
  ok(/lasciate = leave \(imperative\)/.test(src) && !/object[- ]first,? like the Italian|Italian’s object-first/i.test(claims),
    'line 9 is glossed verb-first, and nothing on the page calls object-first order "like the Italian"');
}

/* overflow at three widths */
for (const w of [390, 768, 1440]) {
  await page.setViewportSize({ width: w, height: 900 });
  await page.waitForTimeout(120);
  const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(over <= 1, `no horizontal overflow at ${w}px (overflow=${over})`);
}

/* the shared way-out + banner */
ok(await page.locator('.aw-wayout a[href="/archive/"]').count() === 1, 'canonical way-out footer present');
ok(await page.locator('script[src="/media/home-banner.js"]').count() === 1, 'home banner script present');

ok(errors.length === 0, 'no JS/console errors: ' + errors.join(' | ').slice(0, 200));

await browser.close();
await new Promise(r => server.close(r));
console.log(`abandon-all-hope browser check: ${pass}/${pass + fail} pass`);
process.exit(fail ? 1 : 0);
