// verify-fingerprints.mjs — the check behind /strata/why-fingerprints/.
//
// Two parts:
//   (1) PURE MATH — the load-bearing arithmetic the page asserts: f = v/λ, the
//       lab-probe note (10 Hz), the Pacinian-band crossing (250 Hz ⇒ v = 12.5 cm/s),
//       and the band→speed window. No browser needed.
//   (2) LIVE PAGE — drive the real immersive page in a headless browser: no JS
//       errors, the readout equals v/λ for several slider settings, the verdict
//       flips at the band edges, presets work, and no horizontal overflow at
//       phone / tablet / desktop widths.
//
//   npm run build && node verify-fingerprints.mjs
//
// Reported (NOT re-derived here — quoted from primary sources, trusted):
//   • interridge distance λ ≈ 0.5 mm        — Scheibert et al. companion (arXiv:0911.3226)
//   • dominant frequency = v/λ              — Scheibert et al., Science 323:1503 (2009)
//   • Pacinian peak ~250 Hz (band ~200–300) — vibrotactile literature
//   • fingerprints cut contact area ~33%    — Warman & Ennos, J. Exp. Biol. 212:2016 (2009)
//   • moisture-regulated grip               — Yum, Adams et al., PNAS 117:31665 (2020)

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';

let fails = 0;
const ok = (name, cond, extra = '') => { if (!cond) fails++; console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ---------------------------------------------------------------- (1) MATH
console.log('— the arithmetic the page is built on —');
const f = (v, lam) => v / lam;                 // v in mm/s, λ in mm → Hz

ok('f = v/λ : 5 mm/s ÷ 0.50 mm = 10 Hz (the 2009 lab probe)', f(5, 0.50) === 10, `${f(5,0.50)}`);
ok('f = v/λ : 125 mm/s ÷ 0.50 mm = 250 Hz', f(125, 0.50) === 250, `${f(125,0.50)}`);
ok('f = v/λ : 250 mm/s ÷ 0.50 mm = 500 Hz', f(250, 0.50) === 500, `${f(250,0.50)}`);
// the page's headline match must be DERIVED, not asserted: solve v for f=250 at λ=0.5
const vForPeak = 250 * 0.50;                   // mm/s
ok('Pacinian peak 250 Hz ⇒ v = 12.5 cm/s (natural finger speed)', vForPeak === 125, `${vForPeak} mm/s = ${vForPeak/10} cm/s`);
// band 200–300 Hz at λ=0.5 ⇒ v ∈ [100,150] mm/s = 10–15 cm/s
ok('band 200–300 Hz at λ=0.5 ⇒ v = 10–15 cm/s', 200*0.5 === 100 && 300*0.5 === 150, `${200*0.5}–${300*0.5} mm/s`);
// the lab probe sits well BELOW the band — the honest nuance the page makes
ok('lab probe (10 Hz) is far below the band (200 Hz)', f(5,0.50) < 200, '10 < 200');
// λ sensitivity: a thinner ridge raises the note; the band moves with λ
ok('λ=0.40 mm at v=100 mm/s = 250 Hz (band tracks ridge spacing)', f(100, 0.40) === 250, `${f(100,0.40)}`);
// the audio sonifies the SAME f: one tick every 1/f seconds; taps fuse into a tone ~20 Hz, far below the band
ok('audio period = 1/f : 250 Hz ⇒ 4 ms between ridge ticks', Math.abs((1 / 250) - 0.004) < 1e-9, `${(1/250*1000).toFixed(1)} ms`);
ok('taps→tone fusion (~20 Hz) sits far below the Pacinian band (200 Hz)', 20 < 200, '20 < 200');

// ---------------------------------------------------------------- (2) LIVE PAGE
const root = join(process.cwd(), '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' };
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(8163, r));
const URL_ = 'http://localhost:8163/strata/why-fingerprints/';

console.log('\n— the live page —');
const browser = await chromium.launch({ args: ['--autoplay-policy=no-user-gesture-required'] });
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
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('no JS errors on load', errs.length === 0, errs.join(' | '));

// readout reflects the formula for several settings
async function readoutFor(v, lam) {
  await page.fill('#v', String(v));            // range inputs accept fill in chromium
  await page.$eval('#v', el => el.dispatchEvent(new Event('input', { bubbles: true })));
  await page.fill('#lam', String(lam));
  await page.$eval('#lam', el => el.dispatchEvent(new Event('input', { bubbles: true })));
  return (await page.textContent('#freq')).trim();
}
let r = await readoutFor(125, 0.50);
ok('readout @125,0.50 = 250 Hz', /=\s*250\s*Hz/.test(r), r);
r = await readoutFor(5, 0.50);
ok('readout @5,0.50 = 10 Hz', /=\s*10\s*Hz/.test(r), r);
ok('verdict below band at 10 Hz', /below the band/i.test(await page.textContent('#verdict')));
r = await readoutFor(250, 0.50);
ok('readout @250,0.50 = 500 Hz', /=\s*500\s*Hz/.test(r), r);
ok('verdict above band at 500 Hz', /above the band/i.test(await page.textContent('#verdict')));

// preset buttons drive the instrument
await page.click('.presets button[data-v="125"]');
ok('preset "feeling a fabric" → 250 Hz, in band',
   /=\s*250\s*Hz/.test(await page.textContent('#freq')) && /Pacinian band/i.test(await page.textContent('#verdict')));

// --- audio: the synthesized click-rate must equal v/λ (the same checked number) ---
console.log('\n— hear the ridges (audio sonification) —');
await page.click('#playBtn');
await page.waitForTimeout(90);
ok('audio toggles on (aria-pressed + running)',
   (await page.getAttribute('#playBtn', 'aria-pressed')) === 'true' &&
   (await page.evaluate(() => window.__awFingerAudio && window.__awFingerAudio.running())) === true);
for (const [v, lam] of [[125, 0.50], [5, 0.50], [220, 0.50], [100, 0.40]]) {
  await page.fill('#v', String(v)); await page.$eval('#v', el => el.dispatchEvent(new Event('input', { bubbles: true })));
  await page.fill('#lam', String(lam)); await page.$eval('#lam', el => el.dispatchEvent(new Event('input', { bubbles: true })));
  const rate = await page.evaluate(() => window.__awFingerAudio.rate());
  ok(`audio click-rate = v/λ @${v},${lam} → ${v / lam} Hz`, Math.abs(rate - v / lam) < 1e-9, `got ${rate}`);
}
// the sound-state label crosses taps↔tone across the fusion threshold
await page.fill('#v', '5'); await page.$eval('#v', el => el.dispatchEvent(new Event('input', { bubbles: true })));
await page.fill('#lam', '0.5'); await page.$eval('#lam', el => el.dispatchEvent(new Event('input', { bubbles: true })));
ok('state reads "separate taps" at 10 Hz', /taps/i.test(await page.textContent('#statetxt')), await page.textContent('#statetxt'));
await page.fill('#v', '125'); await page.$eval('#v', el => el.dispatchEvent(new Event('input', { bubbles: true })));
ok('state reads "tone …on the band" at 250 Hz', /tone/i.test(await page.textContent('#statetxt')), await page.textContent('#statetxt'));
// the reference tone (sensor's peak) layers in without error
await page.click('#refBtn');
await page.waitForTimeout(50);
ok('sensor-peak (250 Hz) reference toggles on', (await page.evaluate(() => window.__awFingerAudio.ref())) === true);
// stopping is clean and also stops the reference
await page.click('#playBtn');
await page.waitForTimeout(50);
ok('audio toggles off', (await page.getAttribute('#playBtn', 'aria-pressed')) === 'false' &&
   (await page.evaluate(() => window.__awFingerAudio.running())) === false);
ok('stopping audio also stops the reference tone', (await page.evaluate(() => window.__awFingerAudio.ref())) === false);
ok('no JS errors during audio interaction', errs.length === 0, errs.join(' | '));

// the page actually states the contested grip correction with its source
const body = (await page.textContent('body')).toLowerCase();
ok('page names the 33% contact reduction', body.includes('33%') || body.includes('a third'));
ok('page cites Warman & Ennos 2009', body.includes('warman') && body.includes('2009'));
ok('page cites Scheibert (Science 2009)', body.includes('scheibert'));
ok('page cites the 2020 PNAS moisture study', body.includes('pnas') && body.includes('2020'));
ok('page flags the function as genuinely open', body.includes('open') || body.includes("isn't settled") || body.includes('not settled'));

// no horizontal overflow at three widths
for (const w of [390, 768, 1440]) {
  await page.setViewportSize({ width: w, height: 900 });
  await page.waitForTimeout(60);
  const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(`no horizontal overflow @${w}px`, over <= 1, `overflow ${over}px`);
}

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