#!/usr/bin/env node
// Tier B: drive the BUILT page with Playwright and check what a reader actually
// gets. Node computes the same quantities from the shipped modules and the
// browser's values are compared against them.
//
//   node verify-how-many-cores-do-you-have.mjs
//
import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { chromium } from 'playwright';

const SLUG = 'how-many-cores-do-you-have';
const DIST = new URL('./dist/', import.meta.url).pathname;
const SRC = new URL('./public/', import.meta.url).pathname;
// Serve dist when it has been built, because that is what a reader gets. Force
// public with AW_ROOT=public while developing. Whichever is served, the node
// side below imports its modules FROM THE SAME TREE, so the two sides can never
// silently be comparing different builds.
const ROOT = (process.env.AW_ROOT === 'public' || !fs.existsSync(path.join(DIST, 'strata', SLUG, 'index.html')))
  ? SRC : DIST;
// A dist/ left over from an earlier build is the worst thing this file can be
// pointed at: it would check a page nobody is going to ship, and it would do it
// with a stack trace rather than a verdict. Compare the two trees file by file
// and say so plainly instead.
if (ROOT === DIST) {
  const stale = ['index.html', 'page.js', 'data.js', 'scaling.mjs', 'sweep.mjs', 'workload.mjs', 'browser-run.mjs']
    .filter((f) => {
      const a = path.join(DIST, 'strata', SLUG, f), b = path.join(SRC, 'strata', SLUG, f);
      if (!fs.existsSync(a)) return true;
      return crypto.createHash('sha256').update(fs.readFileSync(a)).digest('hex')
        !== crypto.createHash('sha256').update(fs.readFileSync(b)).digest('hex');
    });
  if (stale.length) {
    console.error(`\ndist/ does not match public/ for this page: ${stale.join(', ')}.`);
    console.error('Build the site first, or run this with AW_ROOT=public. Refusing to check a stale build.\n');
    process.exit(1);
  }
}
const MOD = `${ROOT}strata/${SLUG}/`;
const { reduce, recover, tauWindow, eligibleForWindow, RULES } = await import(MOD + 'scaling.mjs');
const { selfTest } = await import(MOD + 'workload.mjs');
const RESEARCH = new URL(`./research/${SLUG}/`, import.meta.url).pathname;

let pass = 0, fail = 0;
const ok = (name, cond, detail) => {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  [' + detail + ']' : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  [' + detail + ']' : ''}`); }
};

console.log(`serving ${ROOT === DIST ? 'dist/' : 'public/ (dist not built)'}`);

const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript',
  '.json': 'application/json', '.css': 'text/css', '.svg': 'image/svg+xml',
  '.png': 'image/png', '.ico': 'image/x-icon', '.woff2': 'font/woff2' };
const server = http.createServer((req, res) => {
  let url = decodeURIComponent(req.url.split('?')[0]);
  if (url.endsWith('/')) url += 'index.html';
  const f = path.join(ROOT, path.normalize(url).replace(/^(\.\.[/\\])+/, ''));
  if (!f.startsWith(ROOT) || !fs.existsSync(f) || fs.statSync(f).isDirectory()) {
    res.writeHead(404); res.end('missing'); return;
  }
  res.writeHead(200, { 'content-type': TYPES[path.extname(f)] || 'application/octet-stream' });
  res.end(fs.readFileSync(f));
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const PORT = server.address().port;
const URLBASE = `http://127.0.0.1:${PORT}`;

// ---------------------------------------------------------------------------
// what node says, from the shipped modules
// ---------------------------------------------------------------------------
const { DATA, TRACES, CONTROLS } = await import(MOD + 'data.js');
const ground = TRACES.filter((t) => t.truthPhysical !== null && t.mode === 'partition' && !t.cold);
const fitSet = ground.filter((t) => DATA.fitSet.includes(t.id));
const heldOut = ground.filter((t) => DATA.heldOut.includes(t.id));
const nodeSide = {
  selfTest: selfTest().whole,
  tauWin: tauWindow(fitSet),
  recovered: Object.fromEntries(ground.map((t) => [t.id, recover(reduce(t).rows, t.pmax, RULES.tau).value])),
  twoCoreS: (() => { const t = TRACES.find((x) => x.id === 'node-two-cores');
    return t ? reduce(t).rows.find((r) => r.p === 2).S : NaN; })(),
  controlCodes: Object.fromEntries(CONTROLS.map((t) => [t.id, reduce(t).refusals.map((r) => r.code).sort().join(',')]))
};

// ---------------------------------------------------------------------------
const browser = await chromium.launch();
const errors = [], requests = [];
const ctx = await browser.newContext();
const page = await ctx.newPage();
page.on('pageerror', (e) => errors.push('pageerror: ' + String(e)));
page.on('console', (m) => { if (m.type() === 'error') errors.push('console: ' + m.text()); });
page.on('request', (r) => requests.push(r.url()));
await page.goto(`${URLBASE}/strata/${SLUG}/`, { waitUntil: 'networkidle' });
await page.waitForFunction('document.getElementById("check-score").textContent.indexOf("checks pass") > -1'
  + ' || document.getElementById("check-score").textContent.indexOf("threw") > -1', null, { timeout: 30000 });

console.log('\n== the page loads clean');
ok('no JavaScript errors', errors.length === 0, errors.slice(0, 3).join(' | '));
const thirdParty = requests.filter((u) => !u.startsWith(URLBASE) && !u.startsWith('data:'));
ok('no third party requests', thirdParty.length === 0, thirdParty.slice(0, 3).join(' | '));
const missing = [];
for (const u of new Set(requests)) {
  if (!u.startsWith(URLBASE)) continue;
  const r = await ctx.request.get(u);
  if (!r.ok()) missing.push(u + ' -> ' + r.status());
}
ok('every asset the page asks for exists', missing.length === 0, missing.slice(0, 3).join(' | '));

console.log('\n== the check panel');
const score = await page.textContent('#check-score');
ok('the check panel did not throw', !/threw/.test(score), score);
const m = score.match(/^(\d+) \/ (\d+) checks pass$/);
ok('the score parses', !!m, score);
if (m) {
  ok('every check passes', m[1] === m[2], `${m[1]} of ${m[2]}`);
  ok('there are at least 30 checks', Number(m[2]) >= 30, m[2]);
}
const failed = await page.$$eval('#check-list li.bad', (ns) => ns.map((n) => n.textContent.trim()));
ok('no failing rows', failed.length === 0, failed.slice(0, 3).join(' | '));
const categories = await page.$$eval('#check-list li', (ns) => ns.map((n) => n.textContent));
for (const kind of ['GROUND TRUTH', 'CONTROL', 'PROVENANCE', 'NEGATIVE CONTROL', 'OFFLINE:', 'RESTATEMENT']) {
  ok(`the panel carries ${kind} rows`, categories.some((c) => c.includes(kind)),
    String(categories.filter((c) => c.includes(kind)).length));
}

console.log('\n== the browser agrees with node');
const browserSide = await page.evaluate(async () => {
  const s = await import('./scaling.mjs');
  const w = await import('./workload.mjs');
  const d = await import('./data.js');
  const g = d.TRACES.filter((t) => t.truthPhysical !== null && t.mode === 'partition' && !t.cold);
  const fit = g.filter((t) => d.DATA.fitSet.includes(t.id));
  return {
    selfTest: w.selfTest().whole,
    tauWin: s.tauWindow(fit),
    recovered: Object.fromEntries(g.map((t) => [t.id, s.recover(s.reduce(t).rows, t.pmax, s.RULES.tau).value])),
    twoCoreS: (() => { const t = d.TRACES.find((x) => x.id === 'node-two-cores');
      return t ? s.reduce(t).rows.find((r) => r.p === 2).S : NaN; })(),
    controlCodes: Object.fromEntries(d.CONTROLS.map((t) => [t.id, s.reduce(t).refusals.map((r) => r.code).sort().join(',')]))
  };
});
ok('the workload checksum is the same integer in the browser and in node',
  browserSide.selfTest === nodeSide.selfTest, String(nodeSide.selfTest));
ok('the recovered core counts agree',
  JSON.stringify(browserSide.recovered) === JSON.stringify(nodeSide.recovered),
  JSON.stringify(nodeSide.recovered));
ok('every FITTED ground truth capture recovers the answer its affinity mask guarantees',
  fitSet.every((t) => !eligibleForWindow(t) || nodeSide.recovered[t.id] === t.truthPhysical),
  fitSet.map((t) => `${t.id}:${nodeSide.recovered[t.id]}/${t.truthPhysical}`).join(' '));
ok('at least three of the four HELD OUT browser captures do too, and the page prints all four',
  heldOut.filter((t) => nodeSide.recovered[t.id] === t.truthPhysical).length >= heldOut.length - 1,
  heldOut.map((t) => `${t.id}:${nodeSide.recovered[t.id]}/${t.truthPhysical}`).join(' '));
ok('the marginal floor window agrees',
  Math.abs(browserSide.tauWin.lo - nodeSide.tauWin.lo) < 1e-9
  && Math.abs(browserSide.tauWin.hi - nodeSide.tauWin.hi) < 1e-9,
  `${nodeSide.tauWin.lo} to ${nodeSide.tauWin.hi}`);
ok('the shipped window is the recomputed window',
  Math.abs(DATA.tauWin.lo - nodeSide.tauWin.lo) < 1e-9);
ok('the control refusals agree',
  JSON.stringify(browserSide.controlCodes) === JSON.stringify(nodeSide.controlCodes),
  JSON.stringify(nodeSide.controlCodes));

console.log('\n== every figure in the prose is the recomputed value, matched as a string');
const bodyText = await page.textContent('body');
const printed = {
  'the two core speedup in the apparatus': await page.textContent('#ap-s2'),
  'the marginal floor window': await page.textContent('#tau-window'),
  'the default floor': await page.textContent('#tau-default'),
  'the Firefox preference default': await page.textContent('#ff-pref')
};
ok('the apparatus speedup is the reduction\'s',
  printed['the two core speedup in the apparatus'] === nodeSide.twoCoreS.toFixed(3) + 'x',
  printed['the two core speedup in the apparatus']);
ok('the window shown is the window computed',
  printed['the marginal floor window'] === `${nodeSide.tauWin.lo.toFixed(2)} to ${nodeSide.tauWin.hi.toFixed(2)}`,
  printed['the marginal floor window']);
ok('the default floor shown is RULES.tau',
  printed['the default floor'] === RULES.tau.toFixed(2), printed['the default floor']);
ok('the Firefox preference default is the one in the committed source',
  /^\d+$/.test(printed['the Firefox preference default'])
  && fs.readFileSync(RESEARCH + 'data/sources/gecko-StaticPrefList-excerpt.yaml', 'utf8')
    .includes('value: ' + printed['the Firefox preference default']),
  printed['the Firefox preference default']);

console.log('\n== quotations are the committed bytes');
for (const [key, sel] of [['spec-between-1-and', '#q-spec1'], ['spec-err-toward', '#q-spec2'],
  ['amdahl-no-equations', '#q-noeq'], ['amdahl-40-percent', '#q-40'],
  ['amdahl-five-to-seven', '#q-57'], ['amdahl-wasted', '#q-wasted']]) {
  const shown = (await page.textContent(sel)).replace(/^[“"]|[”"]$/g, '').trim();
  const want = DATA.sources.quotes[key].text.trim();
  const file = fs.readFileSync(RESEARCH + 'data/sources/' + DATA.sources.quotes[key].file, 'utf8');
  const norm = (s) => s.replace(/\s+/g, ' ').trim();
  ok(`quotation ${key} is on the page and in the source file`,
    norm(shown) === norm(want) && norm(file).includes(norm(want)), want.slice(0, 45) + '...');
}

console.log('\n== the instrument can return a positive, and a negative');
ok('a string known to be present is present', bodyText.includes('hardwareConcurrency'));
ok('a string known to be absent is absent', !bodyText.includes('lorem ipsum'));
for (const n of ['1021', '1019.9', '1015.8']) {
  ok(`the unverified Gustafson figure ${n} is absent`, !bodyText.includes(n));
}
ok('the held out failure is visible in the page, not only in the notes',
  /held out/i.test(bodyText) && (await page.$$eval('#gt-body tr.wrong', (ns) => ns.length)) >= 1,
  'at least one ground truth row is printed as wrong');
ok('the page names its refusal path', /cannot be measured here/.test(bodyText));

console.log('\n== provenance: shipped data against the lab files');
for (const t of TRACES.concat(CONTROLS)) {
  const raw = fs.readFileSync(RESEARCH + `data/trace-${t.id}.json`);
  const sha = crypto.createHash('sha256').update(raw).digest('hex');
  const lab = JSON.parse(raw);
  ok(`${t.id}: byte identical to the lab source`,
    sha === t.sourceSha256 && JSON.stringify(lab.asc) === JSON.stringify(t.asc),
    sha.slice(0, 12));
}

console.log('\n== the live instrument actually runs');
const before = await page.evaluate(() => {
  const c = document.getElementById('curve');
  return c.getContext('2d').getImageData(0, 0, c.width, c.height).data.some((v) => v !== 0);
});
ok('the speedup canvas is blank before anything is measured', before === false);
await page.selectOption('#depth', 'short');
await page.click('#run');
await page.waitForFunction('document.getElementById("live-state").textContent === "done"', null, { timeout: 180000 });
const after = await page.evaluate(() => {
  const c = document.getElementById('curve');
  const painted = c.getContext('2d').getImageData(0, 0, c.width, c.height).data.some((v) => v !== 0);
  const shown = !document.getElementById('result').hidden;
  const refused = !document.getElementById('refusal').hidden;
  return { painted, shown, refused,
    sentence: document.getElementById('r-sentence').textContent,
    rows: document.querySelectorAll('#sweep-body tr').length,
    hc: navigator.hardwareConcurrency,
    rec: document.getElementById('r-rec').textContent,
    refusalText: document.getElementById('refusal-list').textContent };
});
ok('the sweep either printed a result or refused, never neither',
  after.shown !== after.refused, `shown=${after.shown} refused=${after.refused}`);
if (after.shown) {
  ok('the canvas repainted after the measurement', after.painted === true);
  ok('one row per worker count', after.rows === after.hc, `${after.rows} rows, hc ${after.hc}`);
  ok('the recovered count is between 1 and what the browser claimed',
    Number(after.rec) >= 1 && Number(after.rec) <= after.hc, `${after.rec} of ${after.hc}`);
  ok('the sentence names both numbers',
    after.sentence.includes(String(after.hc)), after.sentence.slice(0, 90));
} else {
  ok('the refusal names a reason', after.refusalText.length > 20, after.refusalText.slice(0, 120));
  console.log('  note: this machine refused the live measurement, which is a valid outcome');
}

console.log('\n== the threshold slider moves the answer');
const slid = await page.evaluate(async () => {
  const el = document.getElementById('tau');
  const read = () => [...document.querySelectorAll('#gt-body tr')].map((r) => r.cells[3].textContent);
  el.value = '-10'; el.dispatchEvent(new Event('input'));
  const low = read();
  el.value = '115'; el.dispatchEvent(new Event('input'));
  const high = read();
  el.value = String(Math.round(0.65 * 100)); el.dispatchEvent(new Event('input'));
  const mid = read();
  const wrongRows = [...document.querySelectorAll('#gt-body tr.wrong')];
  return { low, high, mid, wrongAtDefault: wrongRows.length,
    wrongIds: wrongRows.map((r) => r.cells[0].textContent.trim()) };
});
ok('a floor below zero makes every capture return its full worker count',
  JSON.stringify(slid.low) !== JSON.stringify(slid.mid), slid.low.join(','));
ok('a floor above every recorded gain collapses every capture to one',
  slid.high.every((v) => v === '1'), slid.high.join(','));
ok('at the default floor exactly one capture is wrong, and it is the held out WebKit one',
  slid.wrongAtDefault === 1 && slid.wrongIds.length === 1 && /webkit/i.test(slid.wrongIds[0]),
  slid.wrongIds.join(', '));

console.log('\n== the rendered prose about the engines and the rules');
const glossed = await page.evaluate(() => ({
  webkit: [...document.querySelectorAll('#src-body tr')]
    .map((r) => r.cells[0].textContent).find((s) => /WebKit/.test(s)) || '',
  tauLabel: (document.querySelector('label[for="tau"]') || {}).textContent || '',
  rules: [...document.querySelectorAll('#rules-body tr')].map((r) => r.cells[0].firstChild.textContent.trim()),
  afterShown: (document.getElementById('ap-rules-after') || {}).textContent,
  nShown: (document.getElementById('ap-rules-n') || {}).textContent,
  freqMin: (document.getElementById('ap-freq-min') || {}).textContent,
  freqMax: (document.getElementById('ap-freq-max') || {}).textContent
}));
const noiseLimit = (DATA.sources.quotes['webkit-noise'].text.match(/getUint32\((\d+)\)/) || [])[1];
ok('the WebKit noise range printed is the one the quoted line produces',
  glossed.webkit.includes(`1 to ${noiseLimit}`) && !glossed.webkit.includes('1 to 64'),
  `1 to ${noiseLimit}`);
ok('the marginal floor label says "of a core" exactly once',
  (glossed.tauLabel.match(/of a core/g) || []).length === 1, glossed.tauLabel.trim().slice(0, 90));
const ruleKeys = Object.keys(RULES).filter((k) => !k.endsWith('When'));
const afterKeys = ruleKeys.filter((k) => String(RULES[k + 'When']).startsWith('after'));
ok('the rules table shows every threshold in the reduction',
  ruleKeys.every((k) => glossed.rules.includes(k)) && glossed.rules.length === ruleKeys.length,
  glossed.rules.join(' '));
ok('the prose count of after-the-fact rules is the counted one',
  glossed.afterShown === String(afterKeys.length) && glossed.nShown === String(ruleKeys.length),
  `${glossed.afterShown} of ${glossed.nShown}, computed ${afterKeys.length} of ${ruleKeys.length}`);
const topoFreq = DATA.topology.freq;
ok('the clock range printed is the one the kernel published to the lab script',
  glossed.freqMin === `${topoFreq.minMHz} MHz` && glossed.freqMax === `${topoFreq.maxMHz} MHz`,
  `${glossed.freqMin} to ${glossed.freqMax}`);

console.log('\n== the live controls, run in this browser');
await page.click('#run-ctl');
await page.waitForFunction('/^(done|the controls threw)/.test(document.getElementById("ctl-state").textContent)',
  null, { timeout: 300000 });
const ctl = await page.evaluate(() => ({
  state: document.getElementById('ctl-state').textContent,
  rows: [...document.querySelectorAll('#ctllive-body tr')].map((r) => ({
    name: r.cells[0].textContent.trim(),
    codes: r.cells[3].textContent.trim(),
    verdict: r.cells[4].textContent.trim(),
    wrong: r.classList.contains('wrong')
  }))
}));
ok('the live controls finished without throwing', ctl.state === 'done', ctl.state);
ok('all four live controls ran', ctl.rows.length === 4, ctl.rows.map((r) => r.name).join(', '));
ok('no live control row is printed as a failure of the instrument',
  ctl.rows.length === 4 && ctl.rows.every((r) => !r.wrong),
  ctl.rows.map((r) => `${r.name}:${r.verdict}`).join(' | '));
const sleepRow = ctl.rows.find((r) => /sleep/.test(r.name));
ok('the live sleeping control is caught by the clock free arithmetic rule, not by a timing rule',
  !!sleepRow && sleepRow.codes.includes('work-not-divided') && !sleepRow.codes.includes('impossible-speedup'),
  sleepRow ? sleepRow.codes : 'no sleep row');
ok('what the live table demands of each control is read off the committed twin',
  /liveExpect|CONTROLS\.find\(\(t\) => t\.id === 'control-' \+ mode\)/.test(
    fs.readFileSync(path.join(ROOT, 'strata', SLUG, 'page.js'), 'utf8')));

console.log('\n== accessibility and layout');
const a11y = await page.evaluate(() => {
  const ctrls = [...document.querySelectorAll('input, select, button')];
  const unlabelled = ctrls.filter((c) => {
    if (c.tagName === 'BUTTON') return !c.textContent.trim() && !c.getAttribute('aria-label');
    return !document.querySelector(`label[for="${c.id}"]`) && !c.getAttribute('aria-label');
  }).map((c) => c.id || c.tagName);
  return {
    unlabelled,
    liveRegions: document.querySelectorAll('[aria-live="polite"]').length,
    hiddenCanvases: [...document.querySelectorAll('canvas')].every((c) => c.getAttribute('aria-hidden') === 'true'),
    focusRule: [...document.styleSheets].some((s) => {
      try { return [...s.cssRules].some((r) => /focus-visible/.test(r.cssText)); } catch (e) { return false; }
    }),
    motionRule: [...document.styleSheets].some((s) => {
      try { return [...s.cssRules].some((r) => /prefers-reduced-motion/.test(r.cssText)); } catch (e) { return false; }
    })
  };
});
ok('every control is labelled', a11y.unlabelled.length === 0, a11y.unlabelled.join(','));
ok('there are live regions for the readouts', a11y.liveRegions >= 4, String(a11y.liveRegions));
ok('every canvas is aria-hidden and duplicated in text', a11y.hiddenCanvases === true);
ok('a focus-visible rule ships', a11y.focusRule === true);
ok('a reduced motion rule ships', a11y.motionRule === true);

for (const w of [360, 390, 768, 1200, 1440]) {
  await page.setViewportSize({ width: w, height: 900 });
  const over = await page.evaluate(() => ({
    doc: document.documentElement.scrollWidth,
    win: window.innerWidth
  }));
  ok(`no horizontal overflow at ${w}px`, over.doc <= over.win + 1, `${over.doc} vs ${over.win}`);
}

console.log('\n== the page loads clean under reduced motion');
const ctx2 = await browser.newContext({ reducedMotion: 'reduce' });
const p2 = await ctx2.newPage();
const errs2 = [];
p2.on('pageerror', (e) => errs2.push(String(e)));
await p2.goto(`${URLBASE}/strata/${SLUG}/`, { waitUntil: 'networkidle' });
await p2.waitForFunction('document.getElementById("check-score").textContent.indexOf("checks pass") > -1',
  null, { timeout: 30000 });
const score2 = await p2.textContent('#check-score');
ok('reduced motion: no errors and the panel still runs', errs2.length === 0 && /checks pass/.test(score2), score2);

console.log('\n== the reproduce commands exist');
const reproduce = await page.$$eval('details p.mono', (ns) => ns.map((n) => n.textContent).join('\n'));
const cmds = reproduce.split('\n').map((s) => s.trim()).filter((s) => /^(node|sh) /.test(s));
ok('the apparatus lists reproduce commands', cmds.length >= 8, String(cmds.length));
for (const c of cmds) {
  const f = c.replace(/^(node|sh)\s+/, '').split(' ')[0];
  ok(`the printed command exists: ${f}`, fs.existsSync(new URL('./' + f, import.meta.url).pathname));
}

await browser.close();
server.close();
console.log(`\n${pass} passed, ${fail} failed\n`);
process.exit(fail === 0 ? 0 : 1);
