// verify-the-case-nobody-ran.mjs — the offline check for /strata/the-case-nobody-ran/.
//
//   npm run build && node verify-the-case-nobody-ran.mjs
//   exit 0 = all green, 1 = any failure.
//
// Four things, in order of how much they would hurt to get wrong:
//
//   §1  THE SCANNER, ON GROUND TRUTH. A synthetic fixture with loops whose kinds are known
//       by construction, so the extractor is measured rather than trusted. If the scanner
//       is wrong, every number on the page is wrong in a way no other check would see.
//   §2  THE CENSUS, RE-DERIVED. Agreement and Cohen's κ recomputed from the two readers'
//       raw per-batch files by a route that shares no code with census.mjs, plus the
//       population rebuilt from scan.json under the same published filter.
//   §3  data.json HELD TO IT. Every headline figure the page renders is asserted against
//       the recomputation, so a stale build cannot ship a true-looking number.
//   §4  THE PAGE, IN A REAL BROWSER. No JS errors, the figures actually rendered (a page
//       that fetches its numbers can fail silently and look fine), the filters working,
//       and no horizontal overflow at 390 / 768 / 1440.

import { readFileSync, existsSync, writeFileSync, mkdtempSync, rmSync } from 'fs';
import { createServer } from 'http';
import { tmpdir } from 'os';
import { extname, join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { scan } from './research/unrun-census/lib/loops.mjs';

const ROOT = dirname(fileURLToPath(import.meta.url));
const R = (p) => join(ROOT, p);
const readJSON = (p) => JSON.parse(readFileSync(R(p), 'utf8'));

let pass = 0, fail = 0;
const bad = [];
const ok = (name, cond, detail) => {
  if (cond) { pass++; console.log('  ok    ' + name); }
  else { fail++; bad.push(name + (detail ? ' — ' + detail : '')); console.log('  FAIL  ' + name + (detail ? '   ' + detail : '')); }
};
const eq = (name, got, want) => ok(name, got === want, `got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`);
const near = (name, got, want, eps) => ok(name, Math.abs(got - want) <= eps, `got ${got}, want ${want} ±${eps}`);
const section = (t) => console.log(`\n── ${t} ${'─'.repeat(Math.max(0, 58 - t.length))}`);

/* ════════════════════════════════════════════════════ §1 the scanner, on ground truth */
section('1. The scanner, measured on a fixture whose answers are known');
{
  const fixture = `
    // one plain counted loop whose result is asserted AFTER it, through an accumulator
    // that never READS the counter — a control dependence, which is the commonest shape
    // in this corpus and the one the first scanner missed entirely
    let bad = 0;
    for (let n = 1; n <= 1000; n++) { if (!p(n)) bad++; }
    ok('holds for every n', bad === 0);

    // one asserted INSIDE the body
    for (let k = 0; k < 12; k++) { check('k', f(k) === g(k)); }

    // one that draws randomness: a sample, not an exhaustion
    let s = 0;
    for (let t = 0; t < 500; t++) { s += Math.random() * t; }
    ok('sampled', s > 0);

    // one that never mentions its counter: a repetition, not a per-case check
    let u = 0;
    for (let w = 0; w < 33; w++) { u += 1; }
    ok('repeated', u === 33);

    // one whose result nothing asserts
    for (let i = 0; i < 77; i++) { total += i; }

    // one nested inside a loop whose bound is not a literal
    for (let l = 1; l <= maxLength; l++) {
      for (let t2 = 0; t2 < 4; t2++) { ok('inner', h(t2) === 1); }
    }

    // one whose bound is not a literal at all
    for (let z = 0; z < data.length; z++) { ok('z', q(z)); }
  `;
  const res = scan(fixture, 'fixture.mjs');
  ok('the fixture parses', res.ok, res.error);
  const asserting = res.loops.filter((l) => (l.assertsInside + l.assertsAfter) > 0);
  const population = asserting.filter((l) => !l.random && l.depth === 0);
  eq('counted loops found (literal bounds only, so `data.length` is not one)', res.loops.length, 6);
  eq('loops whose result is asserted', asserting.length, 4);
  eq('…of which two are asserted only after the loop', asserting.filter((l) => l.assertsAfter > 0 && l.assertsInside === 0).length, 2);
  eq('the control-dependent accumulator is followed (this is what the first scanner missed)',
    asserting.some((l) => l.variable === 'n' && l.assertsAfter > 0), true);
  eq('…and the randomized one is detected', asserting.filter((l) => l.random).length, 1);
  eq('a loop that never mentions its counter is a repetition, not a per-case check',
    res.loops.filter((l) => l.variable === 'w' && (l.assertsInside + l.assertsAfter) > 0).length, 0);
  eq('the nested inner loop is marked nested', res.loops.filter((l) => l.depth > 0).length, 1);
  eq('population after the published filter', population.length, 2);
  const first = population.find((l) => l.variable === 'n');
  ok('the 1000-bound loop is found with its counter', !!first);
  if (first) {
    eq('its bound', first.bound, 1000);
    eq('its case count', first.cases, 1000);
    eq('the bound literal sits at the recorded offset',
      fixture.slice(first.boundStart, first.boundEnd), '1000');
  }
  /* The rewrite the experiment arm performs, exercised end to end on the fixture. */
  if (first) {
    const pushed = fixture.slice(0, first.boundStart) + String(first.bound + first.step) + fixture.slice(first.boundEnd);
    ok('the one-more-case rewrite changes exactly the bound',
      pushed.includes('n <= 1001')
      && pushed.slice(0, first.boundStart) === fixture.slice(0, first.boundStart)
      && pushed.slice(first.boundEnd) === fixture.slice(first.boundEnd));
    const emptied = fixture.slice(0, first.boundStart) + String(first.from - first.step) + fixture.slice(first.boundEnd);
    ok('the delete-the-exhaustion rewrite makes the loop run zero times',
      emptied.includes('n = 1; n <= 0'));
  }
}

/* ════════════════════════════════════════════════ §2 the census, re-derived from source */
section('2. The census, re-derived from the committed artifacts');
const scanJson = readJSON('research/unrun-census/scan.json');
const states = readJSON('research/unrun-census/states.json');
const push = existsSync(R('research/unrun-census/push.json')) ? readJSON('research/unrun-census/push.json') : { results: [], baselines: [] };
const data = readJSON('public/strata/the-case-nobody-ran/data.json');

/* The published filter, written out again here rather than imported, so a change to
   census.mjs cannot silently move the population under the page. */
const population = scanJson.rows.filter((r) =>
  (r.assertsInside + r.assertsAfter) > 0 && r.depth === 0 && !r.random
  && !r.file.startsWith('research/unrun-census/'));
eq('population size', population.length, data.headline.population);
eq('files scanned', scanJson.filesScanned, data.headline.filesScanned);
eq('counted loops', scanJson.rows.length, data.headline.countedLoops);

/* The two readers' raw per-batch files, read directly. */
const { readdirSync } = await import('fs');
const loadPass = (dir) => {
  const out = new Map();
  const d = R('research/unrun-census/classify/' + dir);
  for (const f of readdirSync(d).filter((x) => x.endsWith('.json'))) {
    for (const row of JSON.parse(readFileSync(join(d, f), 'utf8'))) if (row && row.id) out.set(row.id, row);
  }
  return out;
};
const A = loadPass('passA'), B = loadPass('passB');
const ids = population.map((r) => `${r.file}:${r.line}`);
eq('reader A covered every loop', ids.filter((i) => A.has(i)).length, population.length);
eq('reader B covered every loop', ids.filter((i) => B.has(i)).length, population.length);

const KINDS = ['complete', 'window', 'resolution', 'fixture'];
const bothIds = ids.filter((i) => A.has(i) && B.has(i));
const agree = bothIds.filter((i) => A.get(i).kind === B.get(i).kind);
eq('loops read by both', bothIds.length, data.headline.bothRead);
eq('loops they agree on', agree.length, data.headline.agree);
/* Cohen's κ, recomputed from the raw files. */
const po = agree.length / bothIds.length;
const pe = KINDS.reduce((acc, k) =>
  acc + (bothIds.filter((i) => A.get(i).kind === k).length / bothIds.length)
      * (bothIds.filter((i) => B.get(i).kind === k).length / bothIds.length), 0);
const kappa = (po - pe) / (1 - pe);
near('Cohen’s κ recomputed from the two readers’ raw files', kappa, data.headline.kappa, 1e-12);
ok('every classification uses only the four published kinds',
  [...A.values(), ...B.values()].every((r) => KINDS.includes(r.kind)));

for (const k of KINDS) {
  eq(`kind "${k}" (both readers agreeing)`,
    bothIds.filter((i) => A.get(i).kind === k && B.get(i).kind === k).length, data.headline.byKind[k]);
}
eq('contested (the readers differ)', bothIds.length - agree.length, data.headline.contested);
eq('contested loops are excluded from every kind count',
  KINDS.reduce((t, k) => t + data.headline.byKind[k], 0) + data.headline.contested, data.headline.population);

/* the "does the page say where it stopped" arm, recomputed */
const stateBy = new Map(states.rows.map((r) => [r.id, r]));
const windowIds = bothIds.filter((i) => A.get(i).kind === 'window' && B.get(i).kind === 'window');
const wCal = windowIds.map((i) => stateBy.get(i)).filter((s) => s && s.owner && s.decoy !== null);
eq('windows in the calibration set', wCal.length, data.headline.statedCalN);
eq('windows whose bound appears in the layer’s prose', wCal.filter((s) => s.stated).length, data.headline.statedYes);
eq('the same test on a same-size decoy', wCal.filter((s) => s.decoyStated).length, data.headline.statedDecoy);
ok('the decoy rate is below the real rate (otherwise the test measures nothing)',
  wCal.filter((s) => s.decoyStated).length < wCal.filter((s) => s.stated).length,
  `${wCal.filter((s) => s.decoyStated).length} vs ${wCal.filter((s) => s.stated).length}`);
ok('every decoy really is a different number of the same digit length',
  states.rows.filter((r) => r.decoy !== null).every((r) =>
    r.decoy !== Math.abs(Math.round(r.bound)) &&
    String(r.decoy).length === String(Math.abs(Math.round(r.bound))).length));

/* the experiment arm, recomputed */
const pushBy = new Map(push.results.map((r) => [`${r.file}:${r.line}`, r]));
const ran = ids.map((i) => pushBy.get(i)).filter(Boolean);
eq('loops run three times', ran.length, data.headline.ran);
if (ran.length) {
  for (const key of ['silent', 'vacuous', 'held']) {
    eq(`delete the exhaustion → ${key}`, ran.filter((r) => r.emptySays === key).length, data.headline.emptySays[key] || 0);
  }
  const held = ran.filter((r) => r.emptySays === 'held');
  eq('loops whose deletion turns the check red', held.length, data.headline.heldN);
  for (const key of Object.keys(data.headline.heldPush)) {
    eq(`of those, one more case → ${key}`, held.filter((r) => r.pushVerdict === key).length, data.headline.heldPush[key]);
  }
  ok('every experiment row records all three runs',
    ran.every((r) => r.emptySays && r.pushVerdict && typeof r.baseMs === 'number'));
  ok('no baseline that was not green produced an experiment row',
    push.baselines.filter((b) => b.verdict !== 'green')
      .every((b) => !push.results.some((r) => r.file === b.file)));
}

/* the browsable list is the whole population, not a flattering slice */
eq('data.json ships every classified loop', data.loops.length, data.headline.population);
ok('every shipped loop carries its file, line and bound',
  data.loops.every((r) => r.f && typeof r.l === 'number' && typeof r.n === 'number'));
ok('the histogram accounts for every loop',
  data.histogram.reduce((t, b) => t + b.n, 0) === data.headline.population,
  String(data.histogram.reduce((t, b) => t + b.n, 0)));

/* ═══════════════════════════════════════════════ §3 the proof this layer points at */
section('3. The proof in section VI');
{
  const leanPath = R('research/hyperbolic-tiling/lean/SchlafliTrichotomy.lean');
  ok('the Lean file exists', existsSync(leanPath));
  if (existsSync(leanPath)) {
    const src = readFileSync(leanPath, 'utf8');
    const code = src.replace(/\/-[\s\S]*?-\//g, ' ').replace(/--.*$/gm, ' ');
    ok('zero imports', !/^\s*import\s/m.test(src));
    ok('no sorry / admit / native_decide in the code', !/\b(sorry|admit|native_decide)\b/.test(code));
    for (const t of ['spherical_iff', 'euclidean_iff', 'hyperbolic_infinite', 'defect_link'])
      ok(`states \`${t}\``, new RegExp(`theorem\\s+${t}\\b`).test(src));
  }
  /* The classification the proof asserts, re-derived here from whole numbers only, by a
     route that shares no code with the proof, the page, or the tiling verifier. */
  const sph = [], euc = [];
  for (let p = 3; p <= 400; p++) for (let q = 3; q <= 400; q++) {
    const l = q * (p - 2), r = 2 * p;
    if (l < r) sph.push(`{${p},${q}}`); else if (l === r) euc.push(`{${p},${q}}`);
  }
  eq('exactly five spherical {p,q} up to 400', sph.join(' '), '{3,3} {3,4} {3,5} {4,3} {5,3}');
  eq('exactly three Euclidean {p,q} up to 400', euc.join(' '), '{3,6} {4,4} {6,3}');
}

/* ═══════════════════════════════════════════════════ §4 the page, in a real browser */
section('4. The page, in a real browser');
const dist = R('dist');
if (!existsSync(join(dist, 'strata', 'the-case-nobody-ran', 'index.html'))) {
  console.log('  SKIP  browser pass — no dist/ build found (run `npm run build` first)');
  console.log(`\nthe-case-nobody-ran · verify\n  ${pass}/${pass + fail} checks pass`);
  if (fail) { bad.forEach((b) => console.log('   ✗ ' + b)); process.exit(1); }
  process.exit(0);
}

const TYPES = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.mjs': 'text/javascript',
  '.json': 'application/json', '.woff2': 'font/woff2', '.png': 'image/png', '.svg': 'image/svg+xml',
  '.ico': 'image/x-icon', '.xml': 'application/xml', '.txt': 'text/plain', '.webp': 'image/webp', '.jpg': 'image/jpeg' };
const server = createServer((req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  try {
    const buf = readFileSync(join(dist, p));
    res.writeHead(200, { 'content-type': TYPES[extname(p)] || 'application/octet-stream' });
    res.end(buf);
  } catch { res.writeHead(404); res.end('404'); }
});
await new Promise((r) => server.listen(8219, r));
const URL_ = 'http://localhost:8219/strata/the-case-nobody-ran/';

const pwMod = await import('/opt/node22/lib/node_modules/playwright/index.js');
const pw = pwMod.chromium ? pwMod : pwMod.default;
const browser = await pw.chromium.launch();
try {
  for (const width of [390, 768, 1440]) {
    const page = await browser.newPage({ viewport: { width, height: 900 } });
    const errs = [];
    page.on('pageerror', (e) => errs.push(String(e)));
    page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });
    await page.goto(URL_, { waitUntil: 'networkidle' });
    ok(`@${width}: no JS errors`, errs.length === 0, errs.join(' | ').slice(0, 200));
    const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
    ok(`@${width}: no horizontal overflow`, overflow <= 1, 'overflow=' + overflow);

    if (width === 1440) {
      /* The figures are fetched, so "the page rendered" and "the page has its numbers"
         are different questions. A page whose fetch failed still looks finished. */
      const stillBlank = await page.$$eval('[data-f]', (els) => els.filter((e) => e.textContent.trim() === '…').length);
      eq('every figure placeholder was filled from data.json', stillBlank, 0);
      const shown = async (name) => (await page.$eval(`[data-f="${name}"]`, (e) => e.textContent)).trim();
      eq('the page prints the population it measured', await shown('population'), data.headline.population.toLocaleString('en-US'));
      eq('the page prints the file count', await shown('filesScanned'), data.headline.filesScanned.toLocaleString('en-US'));
      eq('the page prints κ', await shown('kappa'), data.headline.kappa.toFixed(3));
      eq('the page prints the window count', await shown('windows'), data.headline.byKind.window.toLocaleString('en-US'));

      const cards = await page.$$eval('#stat-row .stat', (e) => e.length);
      ok('the stat row rendered', cards >= 5, 'cards=' + cards);
      const bars = await page.$$eval('#histogram .bar', (e) => e.length);
      ok('the histogram rendered a bar per decade', bars === data.histogram.length, `${bars} vs ${data.histogram.length}`);
      const checks = await page.$$eval('#live-checks li', (e) => e.length);
      ok('the check panel rendered its rows', checks >= 4, 'rows=' + checks);

      /* the browsable list, and the filters actually filtering */
      const all = await page.$$eval('#list .loop', (e) => e.length);
      ok('the list shows the population (capped at 400 per view)', all === Math.min(400, data.headline.population), 'shown=' + all);
      await page.click('.chip[data-filter="kind"][data-value="window"]');
      const wshown = await page.$$eval('#list .loop', (e) => e.length);
      eq('filtering to windows shows exactly the windows', wshown, Math.min(400, data.headline.byKind.window));
      const hits = await page.textContent('#hits');
      ok('the readout reports the filtered count', hits.indexOf(String(data.headline.byKind.window)) === 0, hits.trim());
      await page.fill('#q', 'zzzzznotathing');
      const none = await page.$$eval('#list .loop', (e) => e.length);
      eq('a search that matches nothing shows nothing', none, 0);
    }
    await page.close();
  }
} finally {
  await browser.close();
  server.close();
}

console.log(`\nthe-case-nobody-ran · verify`);
console.log(`  ${pass}/${pass + fail} checks pass`);
if (fail) { console.log('  FAILURES:'); bad.forEach((b) => console.log('   ✗ ' + b)); process.exit(1); }
