// verify-public-key-crypto.mjs — drive the immersive "The Lock That Locks Itself"
// page (/strata/public-key-cryptography/) in a real headless browser: no JS errors;
// the live worked example reproduces the textbook RSA numbers; a generated keypair
// really round-trips a message; decrypting with the public key gives garbage; a
// private-key signature verifies and a tamper is caught; and factoring n breaks the
// key and recovers d.
//   npm run build && node verify-public-key-crypto.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' };
const server = createServer((req,res)=>{ let p=decodeURIComponent(req.url.split('?')[0]); if(p.endsWith('/'))p+='index.html'; const fp=join(root,p);
  try{ const buf=readFileSync(fp); res.writeHead(200,{'content-type':types[extname(fp)]||'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/public-key-cryptography/';

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

ok('no JS errors on load', errs.length===0, errs.join(' | '));

// --- the live worked example reproduces the textbook RSA numbers ---
const tvN   = (await page.textContent('#tv-n')).trim();
const tvPhi = (await page.textContent('#tv-phi')).trim();
const tvD   = (await page.textContent('#tv-d')).trim();
const tvEnc = (await page.textContent('#tv-enc')).trim();
const tvDec = (await page.textContent('#tv-dec')).trim();
ok('worked example n = 3233 (✓)',  tvN.includes('✓') && tvN.includes('3233'), tvN);
ok('worked example φ = 3120 (✓)',  tvPhi.includes('✓') && tvPhi.includes('3120'), tvPhi);
ok('worked example d = 2753 (✓)',  tvD.includes('✓') && tvD.includes('2753'), tvD);
ok('worked example encrypt 65→2790 (✓)', tvEnc.includes('✓') && tvEnc.includes('2790'), tvEnc);
ok('worked example decrypt 2790→65 (✓)', tvDec.includes('✓') && /\b65\b/.test(tvDec), tvDec);

// --- a generated keypair: key fields populate with real numbers ---
const kn = (await page.textContent('#kn')).trim();
const ke = (await page.textContent('#ke')).trim();
const kd = (await page.textContent('#kd')).trim();
ok('public modulus n is a real number', /^\d+$/.test(kn) && BigInt(kn) > 1000n, kn);
ok('public exponent e present', /^\d+$/.test(ke), ke);
ok('private exponent d present', /^\d+$/.test(kd), kd);

// --- encryption round-trips: decrypted text equals the message ---
await page.fill('#msg', 'hello world');
await page.waitForTimeout(50);
const plain = (await page.textContent('#plainOut')).trim();
ok('message round-trips (private key decrypts to the input)', plain.includes('hello world'), plain);
const cipher = (await page.textContent('#cipherOut')).trim();
ok('ciphertext is numbers, not the plaintext', /\d{2,}/.test(cipher) && !cipher.includes('hello'), cipher.slice(0,40));

// --- decrypting with the PUBLIC key gives garbage (not the message) ---
const garble = (await page.textContent('#garbleOut')).trim();
ok('public-key "decrypt" does NOT return the message', !garble.includes('hello world'), garble.slice(0,40));

// --- sign / verify: clean message verifies ---
await page.uncheck('#tamper');
await page.fill('#sigmsg', 'I authorise the transfer');
await page.click('#signBtn');
await page.waitForTimeout(50);
let verdict = (await page.textContent('#sigVerdict')).trim();
ok('a private-key signature verifies with the public key', /verifies/i.test(verdict) && verdict.includes('✓'), verdict);

// --- tamper is caught ---
await page.check('#tamper');
await page.waitForTimeout(50);
verdict = (await page.textContent('#sigVerdict')).trim();
ok('tampering with the signed message is caught', /INVALID/i.test(verdict) && verdict.includes('✗'), verdict);

// --- break the key by factoring (use a small 16-bit key so the test is instant) ---
await page.click('.seg [data-bits="16"]');
await page.waitForTimeout(50);
await page.click('#breakBtn');
await page.waitForFunction(() => /broken/i.test(document.getElementById('brkread').textContent), { timeout: 8000 });
const brk = (await page.textContent('#brkread')).trim();
const brkDetail = (await page.textContent('#brkdetail')).trim();
ok('factoring breaks the key', /broken/i.test(brk), brk);
ok('factoring recovers the secret private key d', /recovered the private key/i.test(brkDetail) && /secret d/i.test(brkDetail), brkDetail.slice(0,80));

await browser.close(); server.close();
console.log(fails ? `\n${fails} FAILED` : '\nAll page checks passed.');
process.exit(fails ? 1 : 0);
