// verify-page.mjs — drive the shipped page in a real browser.
//
// The offline verifier can read the HTML; it cannot tell whether the page WORKS.
// This one boots a static server over public/, loads the page at three widths, and
// checks the things only a browser can answer: no script errors, nothing overflowing
// sideways, the gated panels stay empty until asked and fill when asked, and the
// tables actually render the six rows each that the data says they should.
//
// The gate matters most. The panels carry the plants, so "empty until a click" is a
// claim about behaviour, and a claim about behaviour has to be driven to be checked.
//
// Usage: node research/salience-experiment/blind-rerun/verify-page.mjs

import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';

const require_ = createRequire(import.meta.url);
let chromium;
for (const spec of ['playwright', '/opt/node22/lib/node_modules/playwright/index.js', './node_modules/playwright/index.mjs']) {
  try { ({ chromium } = require_(spec)); break; } catch (e) { /* next */ }
}
if (!chromium) { console.error('playwright not resolvable'); process.exit(2); }

const ROOT = path.resolve(import.meta.dirname, '..', '..', '..');
const PUBLIC = path.join(ROOT, 'public');
const PORT = 8891;
const TYPES = { '.html': 'text/html', '.json': 'application/json', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.png': 'image/png' };

let pass = 0, fail = 0; const failures = [];
const ok = (c, name, detail) => { if (c) { pass++; } else { fail++; failures.push(name + (detail ? ' — ' + detail : '')); } };

const server = http.createServer((req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  const f = path.join(PUBLIC, p);
  if (!f.startsWith(PUBLIC) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) { res.writeHead(404); return res.end('not found'); }
  res.writeHead(200, { 'Content-Type': TYPES[path.extname(f)] || 'application/octet-stream' });
  res.end(fs.readFileSync(f));
});

const run = async () => {
  await new Promise((r) => server.listen(PORT, r));
  const browser = await chromium.launch();
  const url = `http://127.0.0.1:${PORT}/strata/the-cold-read/`;

  for (const [w, h, label] of [[390, 844, 'mobile'], [768, 1024, 'tablet'], [1440, 900, 'desktop']]) {
    const page = await browser.newPage({ viewport: { width: w, height: h } });
    const errors = [];
    page.on('pageerror', (e) => errors.push(String(e)));
    page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
    await page.goto(url, { waitUntil: 'networkidle' });

    ok(errors.length === 0, `${label}: no script errors`, errors.slice(0, 2).join(' | '));
    const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
    ok(overflow <= 1, `${label}: no horizontal overflow`, `${overflow}px`);
    ok(await page.locator('#blind-rerun').count() === 1, `${label}: the blind re-run section is on the page`);
    ok(await page.locator('table.rt').count() === 2, `${label}: both per-kind tables render`);
    const rows = await page.locator('table.rt tbody tr').count();
    ok(rows === 12, `${label}: twelve kind rows across the two tables`, `${rows}`);

    if (label === 'desktop') {
      // The gate: nothing until asked.
      const before = (await page.locator('#drawlist').innerText()).trim();
      ok(before === '', 'the readings panel is empty before the gate is clicked', JSON.stringify(before.slice(0, 40)));
      ok((await page.locator('#repairs').innerText()).trim() === '', 'the repairs panel is empty before it is opened');
      // The specimens are PRINTED on this page, so the planted sentences are of
      // course present: that is what a reader reads. What must never be present
      // before a reader asks is the other half of the pair, the REPAIRED span,
      // because seeing "1953" beside an essay that says 1957 identifies the plant
      // as surely as the key would. So the check is on the clean anchors.
      const bodyText = await page.locator('body').innerText();
      const CLEAN_SPANS = [
        'In 1953, a surgeon named William Scoville',
        'was Hermann Ebbinghaus, who around 1880',
        'about a third of the material was still available',
        'when Henri Becquerel noticed that uranium salts',
        'with a half-life of about 4.47 billion years',
        'was too small by a factor of more than two hundred',
      ];
      const leaked = CLEAN_SPANS.filter((s) => bodyText.includes(s));
      ok(leaked.length === 0,
        'no repaired span is in the rendered page before a reader asks for one',
        leaked.join(' | '));

      await page.locator('#drawgate').click();
      await page.waitForFunction(() => document.querySelectorAll('#drawlist .draw').length > 0, null, { timeout: 20000 });
      const n = await page.locator('#drawlist .draw').count();
      ok(n > 0, 'the readings load when the gate is clicked', `${n} shown`);
      const cells = await page.locator('#cellpick button').count();
      ok(cells === 8, 'all eight cells are selectable', `${cells}`);
      await page.locator('#cellpick button').nth(4).click();
      await page.waitForTimeout(150);
      ok(await page.locator('#drawlist .draw').count() > 0, 'switching cells shows that cell\'s readings');

      await page.locator('#repairs-details summary').click();
      await page.waitForFunction(() => document.querySelectorAll('#repairs .repair').length > 0, null, { timeout: 20000 });
      const reps = await page.locator('#repairs .repair').count();
      ok(reps === 12, 'twelve repairs render, six per specimen', `${reps}`);
      const mismatch = await page.locator('#repairs .tick', { hasText: 'ANCHOR MISMATCH' }).count();
      ok(mismatch === 0, 'no repair shown on the page fails its own anchor check');

      await page.locator('#prompts-details summary').click();
      await page.waitForFunction(() => document.querySelectorAll('#prompts pre').length > 0, null, { timeout: 20000 });
      const prompts = await page.locator('#prompts pre').allInnerTexts();
      ok(prompts.length === 2, 'both prompts render');
      ok(prompts[1].length > prompts[0].length, 'the cued prompt is the longer of the two');
      ok(!/factual:/.test(prompts[0]), 'the blind prompt shown on the page names no kind');
    }
    await page.close();
  }
  await browser.close();
  server.close();
  console.log(`${pass} passed, ${fail} failed`);
  if (fail) { failures.forEach((f) => console.error('  · ' + f)); process.exit(1); }
};

run().catch((e) => { console.error(e); server.close(); process.exit(1); });
