#!/usr/bin/env node
/* Headless-browser check for /strata/made-not-retold/.
   Serves public/ statically and drives the page: it loads without JS errors; the live
   recompute widget computes the right value from scratch and reports a match against the
   committed b-file for all three sequences at several sizes; the collation links resolve
   to real strata; the generated aw-nearby block is present; the check block cites the
   verifier; no horizontal overflow at 390/768/1440. Run: node verify-made-not-retold.mjs */
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { existsSync, statSync } from 'node:fs';
import { join, extname } from 'node:path';
// Resolve playwright across environments: the cloud image, this local box, or a plain dep.
let chromium;
for (const cand of ['/opt/node22/lib/node_modules/playwright/index.js', '/home/liam/tools/node_modules/playwright/index.js', 'playwright']) {
  try { ({ chromium } = await import(cand)); if (chromium) break; } catch { /* try next */ }
}
if (!chromium) { console.error('playwright not found in any known location'); process.exit(2); }

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', '.ico': 'image/x-icon', '.json': 'application/json' };
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();
let pass = 0, fail = 0;
const ok = (cond, label) => { if (cond) { pass++; console.log('  ✓ ' + label); } else { fail++; console.error('  ✗ FAIL: ' + label); } };
const errors = [];

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/made-not-retold/', { waitUntil: 'networkidle' });

ok((await page.locator('h1').innerText()).trim() === 'Made, Not Retold', 'h1 is "Made, Not Retold"');

// drive the recompute widget: (sequence, n) -> expected value, must show a committed-match
async function recompute(seq, n) {
  await page.selectOption('#seq', seq);
  await page.$eval('#nn', (el, v) => { el.value = String(v); el.dispatchEvent(new Event('input', { bubbles: true })); }, n);
  return (await page.locator('#rc-out').innerText());
}
for (const [seq, n, val] of [
  ['topswops', 6, '2,115'], ['topswops', 8, '180,260'],
  ['goe30', 7, '22'], ['goe30', 5, '6'],
  ['leaper', 6, '94'], ['leaper', 8, '2,766'],
]) {
  const out = await recompute(seq, n);
  const norm = out.replace(/,/g, ''), valn = val.replace(/,/g, '');
  ok(norm.includes(valn) && /matches the committed b-file/i.test(out), `recompute ${seq}(${n}) = ${val}, matches committed`);
  ok(!/DISAGREES/.test(out), `recompute ${seq}(${n}) shows no disagreement`);
}

// collation: a healthy number of spine rows, all pointing at real strata
const rows = await page.locator('.spine a.row').count();
ok(rows >= 30, `collation has ${rows} linked member strata (>=30)`);
const hrefs = await page.$$eval('.spine a.row', els => els.map(e => e.getAttribute('href')));
ok(hrefs.every(h => /^\/strata\/[a-z0-9-]+\/$/.test(h)), 'every spine link is a well-formed /strata/<slug>/ URL');

// generated onward block + the check citation
ok(await page.locator('nav.aw-nearby').count() === 1, 'generated aw-nearby onward block present');
ok(/328\s*\/\s*328/.test(await page.locator('.check').innerText()), 'check block cites 328/328 independent recomputations');
ok(/research\/made-not-retold\/verify\.mjs/.test(await page.content()), 'check block cites the offline verifier path');
ok(/coverage audit/i.test(await page.locator('.audit').innerText()), 'the audit section is present and names the coverage audit');

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

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

await browser.close();
server.close();
console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail === 0 ? 0 : 1);
