// verify-page.mjs: drive the shipped page in a real browser and measure what a reader sees.
//
// The lesson this project keeps relearning: a check keyed to the source file measures the
// source file. Whether the certificate a reader actually reads says CERTIFIED, whether the
// sabotage slider actually turns it red, and whether the folded canvas actually has ink in
// it are questions for a browser, not for a regex over HTML.
//
//   node verify-page.mjs [--headed]
//
// Run from research/one-straight-cut/.

import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { extname, join, normalize } from 'node:path';
import { chromium } from 'playwright';

const ROOT = new URL('../../public/', import.meta.url).pathname;
const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml', '.json': 'application/json' };

let pass = 0, fail = 0;
const failures = [];
const ok = (c, label, detail = '') => { if (c) pass++; else { fail++; failures.push(`${label}${detail ? ' :: ' + detail : ''}`); } };

const server = createServer(async (req, res) => {
  let p = normalize(decodeURIComponent(req.url.split('?')[0]));
  if (p.endsWith('/')) p += 'index.html';
  try {
    const buf = await readFile(join(ROOT, p));
    res.writeHead(200, { 'content-type': TYPES[extname(p)] || 'application/octet-stream' });
    res.end(buf);
  } catch { res.writeHead(404).end('not found'); }
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
const base = `http://127.0.0.1:${server.address().port}`;

const browser = await chromium.launch({ headless: !process.argv.includes('--headed') });
const page = await browser.newPage({ viewport: { width: 1200, height: 1400 } });

const consoleErrors = [];
page.on('console', m => { if (m.type() === 'error') consoleErrors.push(m.text()); });
page.on('pageerror', e => consoleErrors.push('pageerror: ' + e.message));

const offOrigin = [];
page.on('request', r => { const u = new URL(r.url()); if (u.origin !== base) offOrigin.push(r.url()); });

await page.goto(`${base}/strata/one-straight-cut/`, { waitUntil: 'networkidle' });
await page.waitForFunction(() => document.getElementById('verdict')?.textContent !== 'working…', null, { timeout: 15000 });

ok(consoleErrors.length === 0, 'page loads with no console errors', consoleErrors.slice(0, 3).join(' | '));
ok(offOrigin.length === 0, 'page makes no off-origin requests', offOrigin.slice(0, 4).join(' | '));

// ── the default shape certifies, and the reader can see that it does ────────
const verdict = await page.textContent('#verdict');
ok(/^CERTIFIED/.test(verdict), 'the default shape reads CERTIFIED to a reader', verdict);
ok((await page.getAttribute('#cert', 'data-ok')) === 'yes', 'the certificate panel is in its passing state');

const checks = await page.$$eval('#checks li', els => els.map(e => ({
  label: e.querySelector('span:nth-child(2)').textContent,
  pass: e.dataset.pass, num: e.querySelector('.num').textContent,
})));
ok(checks.length === 4, 'four checks are shown', `${checks.length} shown`);
ok(checks.every(c => c.pass === 'yes'), 'all four pass on the default shape',
   checks.filter(c => c.pass !== 'yes').map(c => c.label).join('; '));
ok(checks.some(c => /blade/i.test(c.label)), "the blade check is one of the four visible to a reader");

// ── the numbers on screen are the numbers the engine computed ───────────────
const stats = await page.$$eval('#stats div', els => els.map(e => e.textContent.trim()));
ok(stats.length === 4 && stats.some(s => /creases/.test(s)), 'the statistics row is populated', stats.join(' | '));

// ── canvases actually have ink in them ──────────────────────────────────────
async function inkFraction(id) {
  return page.evaluate((sel) => {
    const cv = document.getElementById(sel);
    const c = cv.getContext('2d');
    const d = c.getImageData(0, 0, cv.width, cv.height).data;
    let lit = 0;
    for (let i = 0; i < d.length; i += 4) if (d[i] + d[i + 1] + d[i + 2] > 120) lit++;
    return lit / (d.length / 4);
  }, id);
}
const flatInk = await inkFraction('flat'), foldInk = await inkFraction('folded');
ok(flatInk > 0.01, 'the flat crease pattern is drawn', `${(flatInk * 100).toFixed(2)}% of pixels lit`);
ok(foldInk > 0.01, 'the folded state is drawn', `${(foldInk * 100).toFixed(2)}% of pixels lit`);

// ── every preset certifies, in the browser ──────────────────────────────────
const presets = await page.$$eval('#presets button', els => els.map(e => e.textContent));
for (const name of presets) {
  await page.click(`#presets button:text-is("${name}")`);
  await page.waitForTimeout(120);
  await page.waitForFunction(() => document.getElementById('verdict')?.textContent !== 'working…');
  const v = await page.textContent('#verdict');
  ok(/^CERTIFIED/.test(v), `preset "${name}" certifies in the browser`, v.slice(0, 80));
}

// ── the negative control, driven through the real slider ────────────────────
// This is the check that decides whether any of the above meant anything.
await page.click('#presets button:text-is("five-pointed star")');
await page.waitForTimeout(120);
ok(/^CERTIFIED/.test(await page.textContent('#verdict')), 'back to a certified shape before sabotage');

await page.$eval('#sab', el => { el.value = '50'; el.dispatchEvent(new Event('input', { bubbles: true })); });
await page.waitForTimeout(250);
const sabVerdict = await page.textContent('#verdict');
const sabState = await page.getAttribute('#cert', 'data-ok');
ok(/^REFUSED/.test(sabVerdict), 'rotating one crease by 0.50 deg turns the certificate to REFUSED', sabVerdict.slice(0, 90));
ok(sabState === 'no', 'the certificate panel goes to its failing state');
const sabChecks = await page.$$eval('#checks li', els => els.filter(e => e.dataset.pass === 'no').length);
ok(sabChecks > 0, 'at least one named check fails, so the refusal says which', `${sabChecks} failing`);

// and the blade visibly leaves the outline, which is the reader-facing evidence
const bladeAfter = await page.evaluate(() => {
  const el = [...document.querySelectorAll('#checks li')].find(e => /blade/i.test(e.textContent));
  return el ? el.querySelector('.num').textContent : null;
});
ok(bladeAfter && !/^0/.test(bladeAfter) && !/<1 nm/.test(bladeAfter),
   "the blade's path is reported as having left the outline", String(bladeAfter));

await page.$eval('#sab', el => { el.value = '0'; el.dispatchEvent(new Event('input', { bubbles: true })); });
await page.waitForTimeout(200);
ok(/^CERTIFIED/.test(await page.textContent('#verdict')), 'returning the slider to zero certifies again');

// ── the printable sheet exists, is one page, and refuses to claim accuracy ──
await page.click('#printBtn');
await page.waitForTimeout(200);
const sheets = await page.$$eval('.aw-print-sheet', els => els.length);
ok(sheets === 1, 'printing builds exactly one sheet', `${sheets} sheets`);
const sheetSVG = await page.$eval('.aw-print-sheet svg.fc-pattern', el => ({
  w: el.getAttribute('width'), vb: el.getAttribute('viewBox'), lines: el.querySelectorAll('line').length,
}));
ok(sheetSVG.vb === '0 0 150 150', 'the printed square is 150 mm of true geometry', sheetSVG.vb);
ok(sheetSVG.lines > 10, 'the printed sheet carries the creases', `${sheetSVG.lines} lines`);
const calVerdict = await page.textContent('#calverdict');
ok(/not claiming/.test(calVerdict), 'before measurement the page refuses to claim print accuracy', calVerdict.slice(0, 70));

// the refusal path, which is the one most likely to be left untested
await page.fill('#measured', '40');
await page.click('#applyCal');
await page.waitForTimeout(80);
ok(/mismeasurement|not measured/.test(await page.textContent('#calverdict')),
   'an implausible measurement is refused rather than applied',
   (await page.textContent('#calverdict')).slice(0, 90));
ok((await page.getAttribute('#calib', 'data-state')) === 'uncalibrated', 'and the panel stays uncalibrated');

await page.fill('#measured', '147');
await page.click('#applyCal');
await page.waitForTimeout(80);
ok((await page.getAttribute('#calib', 'data-state')) === 'calibrated', 'a plausible measurement is accepted');
ok(/2\.00%|-2\.00%/.test(await page.textContent('#calverdict')),
   '147 mm against 150 mm is reported as 2% shrink', (await page.textContent('#calverdict')).slice(0, 110));

// a measurement inside a household ruler's resolution must NOT be called an error
await page.fill('#measured', '150.3');
await page.click('#applyCal');
await page.waitForTimeout(80);
ok(/honest reading is that your printer is accurate/.test(await page.textContent('#calverdict')),
   'a sub-resolution difference is reported as "accurate", not as a tiny error',
   (await page.textContent('#calverdict')).slice(0, 120));

await browser.close();
server.close();

console.log(`\nverify-page: ${pass} passed, ${fail} failed`);
for (const f of failures) console.log('  FAIL ' + f);
process.exit(fail ? 1 : 0);
