// verify.mjs — "Who's Holding the Needle" (venom vs poison)
//
// This stratum's load-bearing claims are FACTS from the toxinology literature
// (sourced on the page), plus a small lattice of internally-checkable logic and
// one chemistry computation. A factual-biology verifier can't run an LD50 assay,
// so it does the honest checkable subset:
//   (A) the route -> category mapping is exactly Nelsen et al. (2014), enumerated
//       over every route x every roster member, and each roster entry's textbook
//       category is consistent with its natural delivery route;
//   (B) the tetrodotoxin "twin" really is one molecule used two ways — checked by
//       recomputing the monoisotopic mass of C11H17N3O8 from first principles and
//       confirming both animals point at the identical formula;
//   (C) the page drives in a real headless browser: no JS errors; chips, routes,
//       twin and channel all respond; the verdict label flips with the route; no
//       horizontal overflow at 390 / 768 / 1440 px.
//
//   npm run build && node research/venom-vs-poison/verify.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';

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

// ---------------------------------------------------------------------------
// (A) The taxonomy — Nelsen, Nisani, Cooper, Fox, Gren, Corbit & Hayes (2014),
//     "Poisons, toxungens, and venoms", Biological Reviews 89(2):450-465.
//   poison   = a toxic secretion with NO delivery (ingested / inhaled / absorbed)
//   toxungen = delivered to the body SURFACE, without a wound
//   venom    = delivered to INTERNAL tissue, via a wound
// The page's route -> category map must equal this, exactly.
const ROUTE_TO_CATEGORY = { inject: 'venom', spray: 'toxungen', swallow: 'poison', touch: 'poison' };

// Roster facts, each anchored to a source on the page.
const ROSTER = [
  { id: 'taipan',   natural: 'inject',  category: 'venom',  chem: 'protein' },
  { id: 'bee',      natural: 'inject',  category: 'venom',  chem: 'protein' },
  { id: 'scorpion', natural: 'inject',  category: 'venom',  chem: 'protein' },
  { id: 'cobra',    natural: 'inject',  category: 'venom',  chem: 'protein', also: 'spray' }, // dual-route
  { id: 'octopus',  natural: 'inject',  category: 'venom',  chem: 'small', toxin: 'TTX' },
  { id: 'puffer',   natural: 'swallow', category: 'poison', chem: 'small', toxin: 'TTX' },
  { id: 'frog',     natural: 'touch',   category: 'poison', chem: 'small', toxin: 'BTX' },
  { id: 'pitohui',  natural: 'touch',   category: 'poison', chem: 'small', toxin: 'BTX' },
  { id: 'toad',     natural: 'swallow', category: 'poison', chem: 'small' },
  { id: 'loris',    natural: 'inject',  category: 'venom',  chem: 'protein' },
];

console.log('--- (A) taxonomy: route -> category, and roster consistency ---');
// every roster member's textbook category follows from its natural route
for (const c of ROSTER) {
  ok(`${c.id}: natural route '${c.natural}' implies '${c.category}'`,
     ROUTE_TO_CATEGORY[c.natural] === c.category);
}
// the dual-route case: spitting cobra is venom by bite AND toxungen by spray
const cobra = ROSTER.find(c => c.id === 'cobra');
ok('cobra dual route: bite -> venom, spray -> toxungen',
   ROUTE_TO_CATEGORY[cobra.natural] === 'venom' && ROUTE_TO_CATEGORY[cobra.also] === 'toxungen');

// the TWIN: octopus and puffer share one toxin, opposite categories
const oct = ROSTER.find(c => c.id === 'octopus'), puf = ROSTER.find(c => c.id === 'puffer');
ok('TTX twin: same toxin, opposite category',
   oct.toxin === 'TTX' && puf.toxin === 'TTX' && oct.category !== puf.category,
   `${oct.toxin}:${oct.category} vs ${puf.toxin}:${puf.category}`);
// the BTX pair: frog and pitohui share one toxin, both poison
const frog = ROSTER.find(c => c.id === 'frog'), pit = ROSTER.find(c => c.id === 'pitohui');
ok('BTX pair: same toxin (frog & pitohui), both poison',
   frog.toxin === 'BTX' && pit.toxin === 'BTX' && frog.category === 'poison' && pit.category === 'poison');

// ---------------------------------------------------------------------------
// (B) Tetrodotoxin chemistry: C11H17N3O8. Recompute the monoisotopic mass from
//     the most-abundant isotope masses, and confirm it matches the literature
//     value (~319.10 Da) to a tight tolerance. This anchors the "same molecule"
//     claim to an arithmetic fact rather than an assertion.
console.log('\n--- (B) tetrodotoxin formula C11H17N3O8 ---');
const ISO = { C: 12.000000, H: 1.0078250319, N: 14.0030740052, O: 15.9949146221 }; // monoisotopic
const TTX = { C: 11, H: 17, N: 3, O: 8 };
const mono = TTX.C * ISO.C + TTX.H * ISO.H + TTX.N * ISO.N + TTX.O * ISO.O;
const LIT = 319.1016; // monoisotopic mass of tetrodotoxin (neutral), literature
ok(`monoisotopic mass recomputed = ${mono.toFixed(4)} Da (lit ~${LIT})`, Math.abs(mono - LIT) < 0.01,
   `|Δ| = ${Math.abs(mono - LIT).toFixed(5)}`);
// average (molar) mass sanity check, ~319.27 g/mol
const AVG = { C: 12.011, H: 1.008, N: 14.007, O: 15.999 };
const molar = TTX.C * AVG.C + TTX.H * AVG.H + TTX.N * AVG.N + TTX.O * AVG.O;
ok(`average molar mass = ${molar.toFixed(2)} g/mol (lit ~319.27)`, Math.abs(molar - 319.27) < 0.3);

// ---------------------------------------------------------------------------
// (C) Drive the real page.
console.log('\n--- (C) headless-browser drive ---');
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' };
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(8231, r));
const URL_ = 'http://localhost:8231/strata/venom-vs-poison/';

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

ok('no JS errors on load', errs.length === 0, errs.join(' | '));
ok('roster rendered (10 chips)', (await page.$$('#roster .chip')).length === 10);
ok('routes rendered (4)', (await page.$$('#routes .route')).length === 4);

// default selection is the pufferfish (poison)
ok('default verdict badge = POISON', (await page.textContent('#vbadge')).toLowerCase().includes('poison'));

// switch to the blue-ringed octopus -> auto-selects its natural route (inject) -> VENOM
await page.click('#roster .chip[data-id="octopus"]');
await page.waitForTimeout(60);
ok('octopus -> badge flips to VENOM', (await page.textContent('#vbadge')).toLowerCase().includes('venom'),
   await page.textContent('#vbadge'));

// now force the SAME octopus through the swallow route -> category becomes POISON
await page.click('#routes .route[data-id="swallow"]');
await page.waitForTimeout(60);
ok('octopus + swallow -> badge becomes POISON (category is the route)',
   (await page.textContent('#vbadge')).toLowerCase().includes('poison'));

// the spitting cobra spray route -> TOXUNGEN
await page.click('#roster .chip[data-id="cobra"]');
await page.click('#routes .route[data-id="spray"]');
await page.waitForTimeout(60);
ok('cobra + spray -> badge = TOXUNGEN', (await page.textContent('#vbadge')).toLowerCase().includes('toxungen'),
   await page.textContent('#vbadge'));

// effect-by-route asymmetry: a protein toxin loses width when swallowed vs injected
await page.click('#roster .chip[data-id="taipan"]');
await page.click('#routes .route[data-id="inject"]');
await page.waitForTimeout(60);
const wInject = await page.evaluate(() => parseFloat(document.getElementById('effbar').style.width) || 0);
await page.click('#routes .route[data-id="swallow"]');
await page.waitForTimeout(60);
const wSwallow = await page.evaluate(() => parseFloat(document.getElementById('effbar').style.width) || 0);
ok('protein toxin: injected effect >> swallowed effect', wInject > wSwallow + 40,
   `inject=${wInject}% swallow=${wSwallow}%`);

// a small stable toxin (octopus/TTX) keeps most of its effect when swallowed
await page.click('#roster .chip[data-id="octopus"]');
await page.click('#routes .route[data-id="inject"]');
await page.waitForTimeout(60);
const sInject = await page.evaluate(() => parseFloat(document.getElementById('effbar').style.width) || 0);
await page.click('#routes .route[data-id="swallow"]');
await page.waitForTimeout(60);
const sSwallow = await page.evaluate(() => parseFloat(document.getElementById('effbar').style.width) || 0);
ok('small stable toxin: route barely changes effect', Math.abs(sInject - sSwallow) < 20,
   `inject=${sInject}% swallow=${sSwallow}%`);

// the channel instrument: three states, readout changes
await page.click('#chanctl button[data-state="ttx"]');
await page.waitForTimeout(40);
ok('channel TTX readout mentions plug/block', /plug|no sodium|fire/i.test(await page.textContent('#chanread')));
await page.click('#chanctl button[data-state="btx"]');
await page.waitForTimeout(40);
ok('channel BTX readout mentions open/flood', /open|flood|never stop|won.t/i.test(await page.textContent('#chanread')));

ok('still no JS errors after interaction', errs.length === 0, errs.join(' | '));
await page.close();

// overflow pass
for (const w of [390, 768, 1440]) {
  const pg = await browser.newPage({ viewport: { width: w, height: 1000 } });
  await pg.goto(URL_, { waitUntil: 'networkidle' });
  const sw = await pg.evaluate(() => document.documentElement.scrollWidth);
  const cw = await pg.evaluate(() => document.documentElement.clientWidth);
  ok('no horizontal overflow @' + w, sw <= cw + 1, `scrollW=${sw} clientW=${cw}`);
  await pg.close();
}

await browser.close();
server.close();
console.log(fails === 0 ? '\nPASS — taxonomy consistent, chemistry recomputed, page drives with no errors or overflow.' : `\nFAIL — ${fails} check(s) failed.`);
process.exit(fails === 0 ? 0 : 1);
