#!/usr/bin/env node
/* ── verify-page.mjs ────────────────────────────────────────────────────────
   The other verifier checks that the numbers are right. This one checks that
   the reader's own instrument produces them.

   The 2026-08-10 printable wave shipped a page with 441,475 passing assertions
   and an instrument that gave the wrong answer, because every assertion tested
   the arithmetic and none tested the artefact. So this drives the actual
   controls in a real browser and reads the actual readouts.

   Needs a server for the built site. Run:
     npm run build && npx http-server dist -p 4399 --silent &
     node research/something-has-to-stop-the-loop/verify-page.mjs --base http://localhost:4399
   ────────────────────────────────────────────────────────────────────────── */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

let chromium;
try { ({ chromium } = await import('playwright')); }
catch { ({ chromium } = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default); }

const HERE = path.dirname(fileURLToPath(import.meta.url));
const flag = (name, dflt) => {
  const i = process.argv.indexOf('--' + name);
  return i >= 0 ? process.argv[i + 1] : dflt;
};
const BASE = String(flag('base', 'http://localhost:4399')).replace(/\/$/, '');
const URL_ = BASE + '/strata/something-has-to-stop-the-loop/';
const D = JSON.parse(fs.readFileSync(path.join(HERE, 'data.json'), 'utf8'));

let pass = 0;
const fails = [];
const ok = (name, cond, detail = '') => { if (cond) pass++; else fails.push(name + (detail ? '  [' + detail + ']' : '')); };
const eq = (name, got, want) => ok(name, String(got) === String(want), `got ${got} want ${want}`);

const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });
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' });
await page.waitForTimeout(400);

const text = id => page.textContent('#' + id).then(t => (t || '').trim());
const gridOf = (c, d) => D.grid.find(g => g.convention === c && g.d === d);

/* ── the page loaded and wrote itself ─────────────────────────────────── */
ok('no page errors on load', errors.length === 0, errors.slice(0, 2).join(' | '));
ok('the member figures line was filled in by the page, not typed',
  (await text('repro')).includes('All nine match.'));

/* ── the dictionary bench, at its default setting ─────────────────────── */
eq('bench default: closed classes', await text('r-closed'), D.closedBy.uniform.closedClasses);
eq('bench default: asks to settle', await text('r-iters'), gridOf('uniform', 0.85).iters);
eq('bench default: |lambda2|', await text('r-lam'), gridOf('uniform', 0.85).lambda2.toFixed(6));
eq('bench default: Core mass', await text('r-core'), (100 * D.coreMassByD['0.85']).toFixed(2) + '%');
eq('bench default: the top twelve are the ones the verifier computed',
  (await page.$$eval('#r-top span', ns => ns.map(n => n.textContent))).join(' '),
  gridOf('uniform', 0.85).top.join(' '));
eq('bench default: the verdict', await text('verdict'), 'one answer');

/* ── switch the sink rule, with the dial untouched ────────────────────── */
await page.click('#conv button[data-c="selfloop"]');
await page.waitForTimeout(600);
eq('self-loop rule: closed classes', await text('r-closed'), D.closedBy.selfloop.closedClasses);
eq('self-loop rule: |lambda2| equals the damping factor', await text('r-lam'), gridOf('selfloop', 0.85).lambda2.toFixed(6));
eq('self-loop rule: asks to settle', await text('r-iters'), gridOf('selfloop', 0.85).iters);
ok('self-loop rule: the note names the equality case', (await text('r-note')).includes('equal to d'));
ok('self-loop rule: the top word is one that defines nothing',
  D.dangling.words.includes((await page.$$eval('#r-top span', ns => ns.map(n => n.textContent)))[0]),
  (await page.$$eval('#r-top span', ns => ns.map(n => n.textContent)))[0]);

/* ── take the teleport off, and watch uniqueness go ───────────────────── */
await page.fill('#dslider', '100');
await page.dispatchEvent('#dslider', 'input');
await page.waitForTimeout(1500);
eq('d = 1 shown on the label', await text('dval'), '1.00');
{
  const spread = Number(await text('r-spread'));
  ok('d = 1 with 47 closed classes: the starts disagree maximally', Math.abs(spread - 2) < 1e-3, String(spread));
  eq('and the verdict says how many answers', await text('verdict'), D.closedBy.selfloop.closedClasses + ' answers');
}

/* ── back to the standard patch, still at d = 1 ───────────────────────── */
await page.click('#conv button[data-c="uniform"]');
await page.waitForTimeout(1200);
{
  const spread = Number(await text('r-spread'));
  ok('d = 1 with one closed class: the starts still agree', spread < 1e-10, String(spread));
  eq('and the verdict is one answer', await text('verdict'), 'one answer');
}

/* ── the leak rule drains ─────────────────────────────────────────────── */
await page.click('#conv button[data-c="leak"]');
await page.waitForTimeout(1200);
ok('leak at d = 1: the total mass is gone', Number(await text('r-mass')) < 1e-6, await text('r-mass'));
eq('leak at d = 1: the verdict', await text('verdict'), 'no answer left');
eq('leak: no eigenvalue is claimed', await text('r-lam'), 'n/a');

/* ── the definition solver ────────────────────────────────────────────── */
const solverCase = async (label, expectVerdict, expectAnswer) => {
  await page.waitForTimeout(350);
  eq(`solver ${label}: verdict`, await text('f-verdict'), expectVerdict);
  if (expectAnswer !== null) eq(`solver ${label}: answer`, await text('f-answer'), expectAnswer);
};
for (const def of D.logic.definitions) {
  const btn = await page.$(`#presets button[data-f]`);
  void btn;
}
await page.click('#presets button:nth-child(1)');   // ¬□p
await solverCase('the Gödel sentence', 'one answer', '¬□⊥');
await page.click('#presets button:nth-child(6)');   // ¬p
await solverCase('the liar', 'no answer', null);
ok('the liar answer text says nothing is guaranteed to exist',
  (await text('f-answer')).includes('not guarded'));
await page.click('#presets button:nth-child(7)');   // p
await solverCase('the truth-teller', D.logic.equivalenceClasses + ' answers', null);
await page.click('#presets button:nth-child(9)');   // □□□□□¬p
await solverCase('the deep one', 'not in this space', null);
ok('and it explains that the answer exists but is bigger than the space',
  (await text('f-answer')).includes('Raise the bound'));
await page.click('#sizes button[data-s="6"]');
await page.waitForTimeout(500);
eq('raising the bound finds it', await text('f-answer'), '□□□□□⊥');
eq('and the class count grew with the space', await text('f-classes'), '12');

/* typing a proposition the closed fragment does not have must be refused,
   not silently answered */
await page.fill('#fin', '[](p -> q)');
await page.waitForTimeout(500);
eq('an atom outside the closed fragment is refused', await text('f-verdict'), 'cannot read that');
ok('with a reason', (await text('f-guard')).includes('closed fragment'));

/* ── the ladder ───────────────────────────────────────────────────────── */
{
  const bars = await page.$$eval('#ladder .bv', ns => ns.map(n => n.textContent.trim()));
  eq('the ladder shows every game', bars.length, D.focal.ladder.length);
  eq('and the coin reads what that layer measured', bars[0], Math.round(100 * D.focal.ladder[0].pMatch) + '%');
  eq('and the free word reads zero', bars[bars.length - 1], '0%');
}

/* ── tables ───────────────────────────────────────────────────────────── */
eq('the precomputed grid has a row for every setting',
  (await page.$$eval('#gridtab tbody tr', ns => ns.length)), D.grid.length);
eq('the stopping table has a row for every definition',
  (await page.$$eval('#stoptab tbody tr', ns => ns.length)), D.logic.stoppingByBound.length);
eq('every control row reports agreement',
  (await page.$$eval('#ctrltab tbody tr td:last-child', ns => ns.filter(n => n.textContent.includes('DISAGREES')).length)), 0);

ok('still no page errors after driving everything', errors.length === 0, errors.slice(0, 2).join(' | '));

await browser.close();

if (fails.length) {
  for (const f of fails) console.error('  FAIL  ' + f);
  console.error(`\n${pass} passed, ${fails.length} FAILED`);
  process.exit(1);
}
console.log(`${pass}/${pass} PASS  (the reader's own instrument, driven in a real browser)`);
