// verify-page.mjs — drive the shipped page in a real browser and check that
// what it computes in front of a reader is what the offline apparatus computes.
//
//   node research/what-lincoln-said/verify-page.mjs [--url http://127.0.0.1:8811]
//
// This is the check that matters most for this page, because the page's whole
// claim is that it recomputes rather than asserts. If the browser's alignment
// and the verifier's alignment ever part company, one of them is lying, and
// which one hardly matters.
import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = dirname(fileURLToPath(import.meta.url));
const data = JSON.parse(readFileSync(join(HERE, 'data.json'), 'utf8'));
const argUrl = process.argv.includes('--url') ? process.argv[process.argv.indexOf('--url') + 1] : 'http://127.0.0.1:8811';
const URL = `${argUrl.replace(/\/$/, '')}/strata/what-lincoln-said/`;

let pass = 0, fail = 0;
const ok = (c, m, extra) => { if (c) { pass++; console.log('  ok   ' + m); } else { fail++; console.log('  FAIL ' + m + (extra ? '  ' + extra : '')); } };

let chromium;
try { ({ chromium } = await import('playwright')); }
catch { try { ({ chromium } = await import('playwright-core')); } catch { console.error('playwright not installed: npm i --no-save playwright-core'); process.exit(2); } }

const browser = await chromium.launch({ executablePath: process.env.AW_CHROMIUM || '/opt/pw-browsers/chromium' })
  .catch(() => chromium.launch());
const ctx = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
const page = await ctx.newPage();

const errors = [], requests = [];
page.on('pageerror', e => errors.push(String(e)));
page.on('console', m => { if (m.type() === 'error') errors.push('console: ' + m.text()); });
page.on('request', r => { const u = r.url(); if (!/^(http:\/\/127\.0\.0\.1|http:\/\/localhost|data:|blob:)/.test(u)) requests.push(u); });

const resp = await page.goto(URL, { waitUntil: 'networkidle', timeout: 60000 });
ok(resp && resp.status() === 200, `the page serves 200 at ${URL}`);
await page.waitForTimeout(600);

ok(errors.length === 0, 'no JavaScript errors', errors.slice(0, 3).join(' | '));
ok(requests.length === 0, 'no third-party requests', requests.slice(0, 3).join(' | '));

// -- the instrument agrees with the verifier ---------------------------------
// Drive the two selects across a sample of pairs and read the distance the page
// prints, then compare with data.json's exact matrix.
const ids = [];
for (const o of data.objects) for (const r of o.readings) ids.push(r.id);
const sample = [];
for (let i = 0; i < ids.length; i++) for (let j = 0; j < ids.length; j++) if (i !== j && (i * 31 + j) % 7 === 0) sample.push([ids[i], ids[j]]);
let agreed = 0, checked = 0;
for (const [a, b] of sample.slice(0, 24)) {
  await page.selectOption('#selA', a);
  await page.selectOption('#selB', b);
  const txt = await page.textContent('#ir-out');
  const m = txt.match(/^\s*(\d+)\s+edits/);
  checked++;
  if (m && Number(m[1]) === data.distance[a][b]) agreed++;
  else console.log(`      mismatch ${a} vs ${b}: page said "${(txt || '').slice(0, 40)}", verifier says ${data.distance[a][b]}`);
}
ok(checked > 0 && agreed === checked, `the browser's edit distance equals the verifier's on all ${checked} sampled pairs`);

// A pair whose distance is not zero, so the check above could have failed.
const nz = data.distance[ids[0]][ids[ids.length - 1]];
ok(nz > 0, `control: the sampled pairs are not all identical (one is ${nz} apart)`);

// -- the erosion instrument --------------------------------------------------
await page.locator('#er').evaluate(el => { el.value = '5'; el.dispatchEvent(new Event('input', { bubbles: true })); });
await page.waitForTimeout(200);
const erTxt = await page.textContent('#er-out');
const shown = Number((erTxt.match(/(\d+)\s+words stand/) || [])[1]);
const expected5 = data.invariant.erosion[data.invariant.manuscripts.length - 1].words;
ok(shown === expected5, `at 5 of 5 the page shows ${expected5} words`, `page said ${shown}`);
const lit = Number((erTxt.match(/(\d+)\s+of them are the same word/) || [])[1]);
ok(lit === data.invariant.coreLength, `and ${data.invariant.coreLength} of them identical in every manuscript`, `page said ${lit}`);

await page.locator('#er').evaluate(el => { el.value = '1'; el.dispatchEvent(new Event('input', { bubbles: true })); });
await page.waitForTimeout(200);
const er1 = Number(((await page.textContent('#er-out')).match(/(\d+)\s+words stand/) || [])[1]);
ok(er1 === data.invariant.erosion[0].words, `at 1 of 5 it shows ${data.invariant.erosion[0].words}`, `page said ${er1}`);
ok(er1 > expected5, 'control: raising the bar actually removes words');

// -- the static panels are populated, not empty scaffolding ------------------
for (const sel of ['#wall-panel', '#core-panel', '#here-panel', '#here-lede', '#stemma-panel', '#nps-panel', '#field-panel', '#basler-panel', '#sources', '#check-body', '#caveat-list', '#gridwrap']) {
  const len = (await page.textContent(sel) || '').trim().length;
  ok(len > 40, `${sel} is filled in (${len} chars)`);
}
const rows = await page.locator('#sources tbody tr').count();
const readingCount = data.objects.reduce((s, o) => s + o.readings.length, 0);
ok(rows === readingCount, `the sources table lists all ${readingCount} readings`, `found ${rows}`);
const cells = await page.locator('#gridwrap button[data-a]').count();
ok(cells === readingCount * readingCount, `the grid has ${readingCount}x${readingCount} cells`, `found ${cells}`);

// The page must print the wall's real numbers, not placeholders.
const wallTxt = await page.textContent('#wall-panel');
ok(wallTxt.includes(String(data.memorialVsBliss.changes)), `the wall panel prints ${data.memorialVsBliss.changes} changes`);
// Data-driven, not typed: the division the wall makes changed when the stone
// was read directly, and a hard-coded "Fourscore" here went red for the right
// reason at the wrong moment.
// Whatever kind the one difference turns out to be, the panel must name it.
{
  const diffs = [].concat(data.memorialVsBliss.items.division, data.memorialVsBliss.items.orthographic,
                          data.memorialVsBliss.items.lexical);
  ok(diffs.length > 0, 'control: there is a difference to name');
  for (const d of diffs) ok(wallTxt.includes(d.b), `the wall panel names it (${d.a} -> ${d.b})`);
}

// The stone panels
{
  const st = await page.textContent('#stone-panel');
  ok(st.includes(String(data.stone.lines.length)), `the stone panel prints ${data.stone.lines.length} lines`);
  ok(/not one comma/i.test(st), 'and says the inscription carries no comma');
  ok(data.stone.commas === 0, 'control: and the transcription really has none');
  const cut = await page.locator('#stone-panel .cut').count();
  ok(cut === data.stone.lines.length, `it renders all ${data.stone.lines.length} cut lines`, `found ${cut}`);
  for (const r of data.stone.rejoined) ok(st.includes(r.word), `it names the rejoined word ${r.word}`);
  const sv = await page.textContent('#stone-vs-panel');
  ok(sv.length > 80, '#stone-vs-panel is filled in');
  const rows = await page.locator('#stone-vs-panel tbody tr').count();
  const want = data.withinObject.find(w => w.object === 'memorial').pairs.length;
  ok(rows === want, `it lists all ${want} pairs of readings of the wall`, `found ${rows}`);
}

// The field and Basler panels must print their real figures, not scaffolding.
{
  const ft = await page.textContent('#field-panel');
  const ug = data.field.summary['under-god'];
  ok(ft.includes(`${ug.foundTightAllPages} of ${ug.allPages}`), `the field panel prints ${ug.foundTightAllPages} of ${ug.allPages}`);
  ok(ft.includes('under God'), 'and names the phrase it tested');
  const bt = await page.textContent('#basler-panel');
  ok(bt.includes('Basler'), 'the Basler panel names the edition');
  for (const f of data.basler.footnotes) ok(bt.includes(f.quote.slice(0, 30)), `it quotes footnote ${f.n} verbatim`);
  ok(bt.includes(String(data.basler.failing.length)), `and prints the ${data.basler.failing.length} disagreements`);
}

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

await browser.close();
console.log(`\n${fail ? 'FAIL' : 'OK'} — ${pass}/${pass + fail} browser checks${fail ? `, ${fail} FAILED` : ''}`);
process.exit(fail ? 1 : 0);
