// verify-the-answer-that-cant-be-wrong.mjs — drive the immersive page in a real
// headless browser and confirm that what a reader actually sees is what the
// offline notebook checked.
//
// The notebook (research/the-answer-that-cant-be-wrong/notebook.mjs) proves the
// engine correct against independent ground truth. This verifier proves the
// PAGE is running that engine honestly: that the numbers printed in the DOM are
// the ones the engine produces, that the replicated study figures match the
// published sources quoted beside them, that the four theorems are visible in
// the reader's own browser, and that nothing overflows or throws.
//
//   npm run build && node verify-the-answer-that-cant-be-wrong.mjs
import pw from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync } from 'fs';
import { extname, join } from 'path';

const root = '/home/user/Artificial-Wasteland/dist/';
const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript', '.woff2': 'font/woff2', '.png': 'image/png', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.xml': 'application/xml', '.txt': 'text/plain', '.json': 'application/json', '.webp': 'image/webp' };
const server = createServer((req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  try {
    const buf = readFileSync(join(root, 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(8188, r));
const URL_ = 'http://localhost:8188/strata/the-answer-that-cant-be-wrong/';

let fails = 0;
const ok = (n, c, x = '') => { if (!c) fails++; console.log(`${c ? '  ok' : 'FAIL'}  ${n}${x ? '   ' + x : ''}`); };

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

console.log('\n=== structure ===');
ok('no JS errors on load', errs.length === 0, errs.join(' | '));
ok('the engine module loaded and exposed its test hook',
  await page.evaluate(() => !!(window.__aw && typeof window.__aw.table === 'function')));
for (const id of ['#dist', '#roc', '#tradeoff']) {
  ok(`canvas ${id} present`, await page.$(id) !== null);
}
for (const id of ['#dPrime', '#bandW', '#bandOff', '#solveD', '#solveT']) {
  ok(`control ${id} present`, await page.$(id) !== null);
}
const painted = await page.evaluate(() => {
  const c = document.getElementById('dist'), g = c.getContext('2d');
  const d = g.getImageData(0, 0, c.width, c.height).data;
  let lit = 0;
  for (let i = 0; i < d.length; i += 4) { if (d[i] + d[i + 1] + d[i + 2] > 24) { lit++; if (lit > 200) return true; } }
  return false;
});
ok('the distributions canvas actually renders', painted);

console.log('\n=== the opening claim is computed, not typed ===');
{
  const a = (await page.textContent('#clashA')).trim();
  const b = (await page.textContent('#clashB')).trim();
  ok('the headline 0.70% is rendered from the counts', a === '0.70%', 'got ' + a);
  ok('the headline 66.19% is rendered from the counts', b === '66.19%', 'got ' + b);
  const spread = await page.evaluate(() => {
    const { rates, tableFromCounts, STUDIES } = window.__aw;
    const R = rates(tableFromCounts(STUDIES.find((s) => s.key === 'ames2b').counts));
    return R.error.fp / R.correct.fp;
  });
  ok('the stated factor of 94 is the real ratio', Math.abs(spread - 94) < 1, spread.toFixed(2) + 'x');
}

console.log('\n=== replication: every published rate quoted on the page ===');
{
  const results = await page.evaluate(() => {
    const { rates, tableFromCounts, STUDIES } = window.__aw;
    const out = [];
    for (const S of STUDIES) {
      const R = rates(tableFromCounts(S.counts));
      for (const p of S.published) {
        const got = p.matches.side === 'fp' ? R[p.matches.convention].fp : R[p.matches.convention].fn;
        out.push({ key: S.key, who: p.who, expect: p.expect, got });
      }
    }
    return out;
  });
  ok('the page carries 13 published figures to replicate', results.length === 13, results.length + ' found');
  for (const r of results) {
    const printed = (100 * r.expect).toPrecision(12).replace(/0+$/, '');
    const dp = ((printed.split('.')[1] || '').replace(/0+$/, '')).length;
    const tol = 0.5 * Math.pow(10, -dp) / 100 + 1e-12;
    ok(`${r.key} reproduces ${(100 * r.expect).toFixed(Math.max(dp, 1))}% (${r.who})`,
      Math.abs(r.got - r.expect) <= tol, (100 * r.got).toFixed(4) + '%');
  }
}

console.log('\n=== the four theorems, in the reader\'s own browser ===');
{
  // Theorem 1 — ordering, on 20k random tables computed by the SHIPPED engine.
  const bad = await page.evaluate(() => {
    const { table, rates } = window.__aw;
    let bad = 0, s = 1;
    const rnd = () => (s = (s * 1103515245 + 12345) % 2147483648) / 2147483648;
    for (let i = 0; i < 20000; i++) {
      const d = rnd() * 5, t1 = (rnd() - 0.5) * 8, t2 = (rnd() - 0.5) * 8;
      const R = rates(table(d, Math.min(t1, t2), Math.max(t1, t2)));
      if (!(R.correct.fp <= R.ignorable.fp + 1e-15 && R.ignorable.fp <= R.error.fp + 1e-15)) bad++;
    }
    return bad;
  });
  ok('THEOREM 1: correct <= ignorable <= error on 20k random tables in-browser', bad === 0, 'violations ' + bad);

  // Theorem 2 — the vanishing act, and its exp(-w d') decay law.
  const van = await page.evaluate(() => {
    const { table, bandAt, convention, answerRate } = window.__aw;
    const ig = convention('ignorable'), d = 1;
    const at = (w) => { const b = bandAt(d, w); const T = table(d, b.tLo, b.tHi); return [ig.fp(T), answerRate(T)]; };
    const law = (() => { const b = bandAt(1, 5); const T = table(1, b.tLo, b.tHi); return Math.log(T.non.id / T.non.el) / -5; })();
    return { w0: at(0), w3: at(3), w12: at(12), law };
  });
  ok('THEOREM 2: the honest no-band rate is 30.85%', Math.abs(van.w0[0] - 0.308537538) < 1e-7, (100 * van.w0[0]).toFixed(4) + '%');
  ok('THEOREM 2: widening the band collapses the rate', van.w3[0] < van.w0[0] / 8,
    `${(100 * van.w3[0]).toFixed(2)}% at w=3, answering ${(100 * van.w3[1]).toFixed(2)}%`);
  ok('THEOREM 2: it goes to zero (w=12 under 0.001%)', van.w12[0] < 1e-5, van.w12[0].toExponential(2));
  ok('THEOREM 2: the decay exponent is d\' = 1 as the page states', Math.abs(van.law - 1) < 0.06, van.law.toFixed(4));

  // Theorem 3 — the inversion, exactly as the table on the page shows it.
  const inv = await page.evaluate(() => {
    const { table, bandAt, convention, auc, answerRate } = window.__aw;
    const ig = convention('ignorable');
    const mk = (d, w) => { const b = bandAt(d, w); const T = table(d, b.tLo, b.tHi); return { fp: ig.fp(T), fn: ig.fn(T), ans: answerRate(T), auc: auc(d) }; };
    return { A: mk(2.5, 0.15), B: mk(1.0, 3.0) };
  });
  ok('THEOREM 3: A is the better examiner', inv.A.auc > inv.B.auc, `${inv.A.auc.toFixed(3)} vs ${inv.B.auc.toFixed(3)}`);
  ok('THEOREM 3: B reports the better false-positive rate anyway', inv.B.fp < inv.A.fp,
    `${(100 * inv.B.fp).toFixed(2)}% < ${(100 * inv.A.fp).toFixed(2)}%`);
  ok('THEOREM 3: and the better false-negative rate', inv.B.fn < inv.A.fn);
  ok('THEOREM 3: B answers far less', inv.B.ans < inv.A.ans / 10,
    `${(100 * inv.B.ans).toFixed(2)}% vs ${(100 * inv.A.ans).toFixed(1)}%`);

  // Theorem 4 — the centred band makes an abstention exactly uninformative.
  const lr = await page.evaluate(() => {
    const { table, bandAt, likelihoodRatios } = window.__aw;
    let worst = 0;
    for (const d of [0.5, 1, 2, 3.5]) for (const w of [0.1, 0.5, 1, 2, 3]) {
      const b = bandAt(d, w);
      worst = Math.max(worst, Math.abs(likelihoodRatios(table(d, b.tLo, b.tHi)).inc - 1));
    }
    const sk = bandAt(2, 1, 0.6);
    return { worst, skew: likelihoodRatios(table(2, sk.tLo, sk.tHi)).inc };
  });
  ok('THEOREM 4: centred band => LR(inconclusive) = 1 exactly', lr.worst < 1e-12, 'max |LR-1| = ' + lr.worst.toExponential(2));
  ok('THEOREM 4: an off-centre band loads the abstention with evidence', Math.abs(lr.skew - 1) > 0.1, 'LR = ' + lr.skew.toFixed(3));
}

console.log('\n=== the instruments respond, and say true things ===');
{
  // Move the band slider and confirm the readouts and the LR text both follow.
  const set = async (sel, v) => {
    await page.evaluate(([s, val]) => {
      const el = document.querySelector(s); el.value = String(val);
      el.dispatchEvent(new Event('input', { bubbles: true }));
    }, [sel, v]);
    await page.waitForTimeout(40);
  };
  await set('#dPrime', 1); await set('#bandOff', 0); await set('#bandW', 0.2);
  const narrow = (await page.textContent('#roomConv')).replace(/\s+/g, ' ');
  await set('#bandW', 3.0);
  const wide = (await page.textContent('#roomConv')).replace(/\s+/g, ' ');
  ok('widening the band changes the reported rates on screen', narrow !== wide);

  const lrText = (await page.textContent('#lrOut')).replace(/\s+/g, ' ');
  ok('with the band centred the page says the abstention carries no information',
    /exactly 1/.test(lrText), lrText.slice(0, 120));
  await set('#bandOff', 0.8);
  const lrSkew = (await page.textContent('#lrOut')).replace(/\s+/g, ' ');
  ok('shifting the band off centre changes that statement', !/exactly 1/.test(lrSkew) && /not neutral/.test(lrSkew),
    lrSkew.slice(0, 120));
  await set('#bandOff', 0);

  // The solver must price its own answer honestly.
  await set('#solveD', 1); await set('#solveT', 3);
  const solve = (await page.textContent('#solveOut')).replace(/\s+/g, ' ');
  ok('the solver reports both the band and the price in declined comparisons',
    /half-width/.test(solve) && /answer/.test(solve) && /one in/.test(solve), solve.slice(0, 150));

  // Study switching rebuilds the tables from the other study's counts.
  const before = await page.textContent('#countTable');
  await page.click('.pills [data-study="ames1"]');
  await page.waitForTimeout(60);
  const after = await page.textContent('#countTable');
  ok('switching study rebuilds the counts table', before !== after);
  ok('Ames I counts appear (1,421 correct eliminations)', /1,421/.test(after), after.replace(/\s+/g, ' ').slice(0, 120));
  const q = await page.textContent('#quotes');
  ok('the source quote for Ames I is present verbatim',
    /22\/2178 = 0\.01010/.test(q));
  await page.click('.pills [data-study="ames2b"]');
  await page.waitForTimeout(60);
}

console.log('\n=== honesty surfaces are actually on the page ===');
{
  const body = (await page.textContent('body')).replace(/\s+/g, ' ');
  ok('the model is declared a cartoon', /is a cartoon/.test(body));
  ok('the withdrawn technical report is disclosed', /withdrawn from the internet/.test(body));
  ok('the beta-binomial caveat is stated', /beta-binomial/.test(body));
  ok('the prior claim is attributed to Dror and Scurich', /Dror and Scurich/.test(body) || /Dror &amp; Scurich/.test(body) || /Dror & Scurich/.test(body));
  ok('the opposing case is quoted, not paraphrased away', /contradiction in terms/.test(body));
  ok('the practitioners\' defence is present', /check against bad/.test(body));
  ok('the NRC 2009 sentence is quoted', /no forensic method has been rigorously shown/.test(body));
  ok('the 2015 FBI review figures are present', /257 \(96 percent\)/.test(body));
  ok('the 96 vs 102 discrepancy is named rather than smoothed', /102/.test(body) && /12\.5/.test(body));
  ok('the show-the-check panel names the notebook', /notebook\.mjs/.test(body));
  const srcCount = await page.evaluate(() => document.querySelectorAll('#sources li').length);
  ok('the sources list is populated', srcCount >= 12, srcCount + ' entries');
  const links = await page.evaluate(() => [...document.querySelectorAll('#sources a')].map((a) => a.href));
  ok('every source entry carries a link', links.length >= 12 && links.every((h) => /^https?:/.test(h)), links.length + ' links');
}

console.log('\n=== layout ===');
for (const w of [360, 390, 768, 1440]) {
  await page.setViewportSize({ width: w, height: 900 });
  await page.waitForTimeout(160);
  const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(`no horizontal overflow at ${w}px`, over <= 1, 'overflow=' + over + 'px');
}
ok('no JS errors after full interaction', errs.length === 0, errs.join(' | '));

await browser.close(); server.close();
console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}`);
process.exit(fails === 0 ? 0 : 1);
