// verify-page.mjs — drive the "Before You Looked" portal in a real browser,
// confirm every instrument produces the numbers the offline verifier expects.
//
// Run:  npx playwright install chromium  (once)
//        node research/before-you-looked/verify-page.mjs
//
// Requires the site running at the URL below (port may be overridden with
// PORT env var). Default port 8132 matches the other physics-seam verifiers.

/* Resolve playwright portably, the house pattern (scripts/headless-check.mjs,
   scripts/og/generate.mjs): this repo's package.json deliberately carries only
   astro, so a bare `from 'playwright'` dies with ERR_MODULE_NOT_FOUND in a clean
   checkout and the check reads as broken when the toolchain is fine. Added
   2026-08-01, when the page-emptying sweep found 13 checks that could not run at
   all in a fresh container: a check that cannot run is a check that cannot fail. */
let chromium;
try { ({ chromium } = await import('playwright')); }
catch { ({ chromium } = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default); }
const PORT = process.env.PORT || '8132';
const URL = `http://127.0.0.1:${PORT}/strata/before-you-looked/`;
const errors = [];
const b = await chromium.launch();

async function run(width, label) {
  const ctx = await b.newContext({ viewport: { width, height: 1000 }, deviceScaleFactor: 1 });
  const p = await ctx.newPage();
  p.on('console', m => { if (m.type() === 'error') errors.push(`[${label}] console.error: ${m.text()}`); });
  p.on('pageerror', e => errors.push(`[${label}] pageerror: ${e.message}`));
  await p.goto(URL, { waitUntil: 'networkidle' });
  await p.waitForTimeout(300);

  // No horizontal overflow
  const ov = await p.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  if (ov > 1) errors.push(`[${label}] horizontal overflow: ${ov}px`);

  // ── INSTRUMENT 1 — the scoreboard ───────────────────────────────────────
  // Initially: three game-rows, no rounds yet, classical bars at their ceilings.
  const initRows = await p.$$eval('#board .game-row', els => els.length);
  if (initRows !== 3) errors.push(`[${label}] scoreboard rows expected 3, got ${initRows}`);

  // Play 200 rounds three times — at 600 the σ on CHSH-quantum is ~0.014, well
  // inside the +/- 5pp window. (The button samples 200 each press.)
  await p.click('#play200');
  await p.waitForTimeout(40);
  await p.click('#play200');
  await p.waitForTimeout(40);
  await p.click('#play200');
  await p.waitForTimeout(200);
  const board = await p.evaluate(() => {
    return window.__byl.games.map(g => ({
      name: g.name,
      cRate: g.runs ? g.cWins / g.runs : null,
      qRate: g.runs ? g.qWins / g.runs : null,
      runs: g.runs,
    }));
  });
  // CHSH classical → ~0.75 (σ on 600 ≈ 0.018 ⇒ ±0.05 is well above 3σ)
  if (!(board[0].cRate > 0.70 && board[0].cRate < 0.80))
    errors.push(`[${label}] CHSH classical rate off: ${board[0].cRate}`);
  // CHSH quantum → ~0.8536 (σ on 600 ≈ 0.014 ⇒ ±0.05 is well above 3σ)
  if (!(board[0].qRate > 0.80 && board[0].qRate < 0.92))
    errors.push(`[${label}] CHSH quantum rate off: ${board[0].qRate}`);
  // GHZ classical → ~0.75 (the strategy we coded wins exactly 3 of 4 inputs)
  if (!(board[1].cRate > 0.70 && board[1].cRate < 0.80))
    errors.push(`[${label}] GHZ classical rate off: ${board[1].cRate}`);
  // GHZ quantum → exactly 1
  if (board[1].qRate !== 1) errors.push(`[${label}] GHZ quantum not 100: ${board[1].qRate}`);
  // EV "quantum" (= P(dark)) → ~0.25 (σ on 600 ≈ 0.018)
  if (!(board[2].qRate > 0.20 && board[2].qRate < 0.30))
    errors.push(`[${label}] EV dark rate off: ${board[2].qRate}`);
  // EV classical bar should remain at 0
  if (board[2].cRate !== 0) errors.push(`[${label}] EV classical bar nonzero: ${board[2].cRate}`);
  if (board[0].runs !== 600) errors.push(`[${label}] runs counter off: ${board[0].runs}`);

  // ── INSTRUMENT 2 — the Mermin contradiction ─────────────────────────────
  // Initial: all +1. Should satisfy exactly 1 of 4 equations (XXX = +1 only).
  const initSat = await p.evaluate(() => {
    let s = 0;
    for (const eq of window.__byl.EQUATIONS) {
      const prod = eq.vars.map(k => window.__byl.M_VALUES[k]).reduce((a, b) => a * b, 1);
      if (prod === eq.req) s++;
    }
    return s;
  });
  if (initSat !== 1) errors.push(`[${label}] initial Mermin sat expected 1, got ${initSat}`);

  // The product row should show the +1 = −1 contradiction.
  const contraText = await p.textContent('#meqs tr.product');
  if (!/\+1\s*=\s*−1|\+1\s*=\s*-1/.test(contraText))
    errors.push(`[${label}] Mermin product row missing +1=−1: ${contraText}`);

  // Try every assignment — verdict should report 0 satisfy all four, 3 is max.
  await p.click('#mTryAll');
  await p.waitForTimeout(80);
  const verdict = (await p.textContent('#merminVerdict')).replace(/\s+/g, ' ');
  if (!/0/.test(verdict) || !/3/.test(verdict))
    errors.push(`[${label}] Mermin tryAll verdict bad: ${verdict.slice(0, 120)}`);

  // After tryAll the displayed assignment satisfies exactly 3 of 4.
  const afterSat = await p.evaluate(() => {
    let s = 0;
    for (const eq of window.__byl.EQUATIONS) {
      const prod = eq.vars.map(k => window.__byl.M_VALUES[k]).reduce((a, b) => a * b, 1);
      if (prod === eq.req) s++;
    }
    return s;
  });
  if (afterSat !== 3) errors.push(`[${label}] after tryAll Mermin sat expected 3, got ${afterSat}`);

  // Equation table has 4 equation rows + 1 product row = 5
  const meqsRows = await p.$$eval('#meqs tr', els => els.length);
  if (meqsRows !== 5) errors.push(`[${label}] meqs rows expected 5, got ${meqsRows}`);

  // ── INSTRUMENT 3 — the bomb tally ───────────────────────────────────────
  await p.click('#b10000');
  await p.waitForTimeout(120);
  const bomb = await p.evaluate(() => ({ ...window.__byl.bomb }));
  const pBoom = bomb.boom / bomb.total;
  const pDark = bomb.dark / bomb.total;
  const pBright = bomb.bright / bomb.total;
  if (Math.abs(pBoom - 0.5) > 0.02) errors.push(`[${label}] bomb P(boom) off: ${pBoom}`);
  if (Math.abs(pDark - 0.25) > 0.02) errors.push(`[${label}] bomb P(dark) off: ${pDark}`);
  if (Math.abs(pBright - 0.25) > 0.02) errors.push(`[${label}] bomb P(bright) off: ${pBright}`);
  if (bomb.total !== 10000) errors.push(`[${label}] bomb total expected 10000, got ${bomb.total}`);

  const bombSummary = await p.textContent('#bombTot');
  if (!/10000/.test(bombSummary)) errors.push(`[${label}] bomb summary missing count: ${bombSummary.slice(0, 80)}`);

  // ── Spine cards present, each links to its stratum ──────────────────────
  const cardCount = await p.$$eval('figure.spine .card', els => els.length);
  if (cardCount !== 3) errors.push(`[${label}] spine cards expected 3, got ${cardCount}`);
  const hrefs = await p.$$eval('figure.spine .card', els => els.map(e => e.getAttribute('href')));
  for (const want of ['/strata/a-game-you-shouldnt-win/', '/strata/the-ghz-game/', '/strata/seeing-in-the-dark/']) {
    if (!hrefs.includes(want)) errors.push(`[${label}] spine card missing href: ${want}`);
  }

  // Screenshots for the desktop pass
  if (label === 'desktop') {
    await p.click('#mTryAll');
    await (await p.$('#i2')).scrollIntoViewIfNeeded(); await p.waitForTimeout(120);
    await p.screenshot({ path: '/tmp/byl-mermin.png' });
    await (await p.$('#i1')).scrollIntoViewIfNeeded(); await p.waitForTimeout(120);
    await p.screenshot({ path: '/tmp/byl-board.png' });
  }

  console.log(`[${label}] overflow=${ov}px CHSH(c,q)=(${board[0].cRate.toFixed(3)},${board[0].qRate.toFixed(3)}) GHZ(c,q)=(${board[1].cRate.toFixed(3)},${board[1].qRate.toFixed(3)}) EV(c,q)=(${board[2].cRate.toFixed(3)},${board[2].qRate.toFixed(3)}) bomb=(${pBoom.toFixed(3)},${pDark.toFixed(3)},${pBright.toFixed(3)}) merminBest=${afterSat}`);
  await ctx.close();
}

await run(1100, 'desktop');
await run(390, 'mobile');
await b.close();

if (errors.length) { console.log('\nERRORS:\n' + errors.join('\n')); process.exit(1); }
console.log('\nALL BROWSER CHECKS PASSED.');
