#!/usr/bin/env node
// verify-page.mjs — open the BUILT immersive page in a real headless browser and
// assert every load-bearing number it prints equals the figure the offline
// verifier proved (research/index-of-coincidence/verify.mjs → artifact.json).
// This is the leash: the page recomputes its numbers live from engine.js, and
// this driver guarantees those live numbers can't drift from the proof.
//
// Usage:  npm run build && node research/index-of-coincidence/verify-page.mjs
// Serves dist/ on an ephemeral local port; no separate server process needed.
// Exit 0 if every check passes, 1 otherwise.

import pw from "/opt/node22/lib/node_modules/playwright/index.js";
const { chromium } = pw;
import http from "node:http";
import { readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dir = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.join(__dir, "..", "..");
const DIST = path.join(ROOT, "dist");

const artifact = JSON.parse(await readFile(path.join(__dir, "artifact.json"), "utf8"));

const MIME = { ".html":"text/html", ".css":"text/css", ".js":"text/javascript",
  ".mjs":"text/javascript", ".woff2":"font/woff2", ".json":"application/json",
  ".svg":"image/svg+xml", ".png":"image/png", ".jpg":"image/jpeg", ".mp4":"video/mp4",
  ".webmanifest":"application/manifest+json" };

const server = http.createServer(async (req, res) => {
  try {
    let p = decodeURIComponent(req.url.split("?")[0]);
    if (p.endsWith("/")) p += "index.html";
    const fp = path.join(DIST, p);
    if (!existsSync(fp)) { res.writeHead(404); res.end("nf"); return; }
    const body = await readFile(fp);
    res.writeHead(200, { "Content-Type": MIME[path.extname(fp)] || "application/octet-stream" });
    res.end(body);
  } catch (e) { res.writeHead(500); res.end(String(e)); }
});
await new Promise(r => server.listen(0, r));
const port = server.address().port;
const url = `http://localhost:${port}/strata/the-cipher-couldnt-hide/`;

let fail = 0;
const ok = m => console.log("  \x1b[32m✓\x1b[0m " + m);
const bad = m => { fail++; console.log("  \x1b[31m✗ " + m + "\x1b[0m"); };
const num = (s) => parseFloat(String(s).replace(/[^0-9.\-]/g, ""));
const T = (label, got, want, tol = 5e-5) => {
  const g = num(got);
  Math.abs(g - want) <= tol ? ok(`${label} → ${got} (artifact ${want})`)
                            : bad(`${label} → printed ${got}, artifact ${want}`);
};

const browser = await chromium.launch();
const page = await browser.newPage();
const errors = [];
page.on("console", m => { if (m.type() === "error") errors.push(m.text()); });
page.on("pageerror", e => errors.push(String(e)));
await page.setViewportSize({ width: 1100, height: 1600 });
await page.goto(url, { waitUntil: "networkidle" });
await page.waitForTimeout(250);

console.log("\nWhat the Cipher Couldn't Hide — page driver\n");

// --- no layout overflow at three widths ---
for (const w of [390, 768, 1100]) {
  await page.setViewportSize({ width: w, height: 1400 });
  await page.waitForTimeout(120);
  const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
  overflow <= 1 ? ok(`${w}px — no horizontal overflow (${overflow}px)`) : bad(`${w}px — overflows by ${overflow}px`);
}
await page.setViewportSize({ width: 1100, height: 1600 });
await page.waitForTimeout(120);

// --- the film is embedded and points at the real asset ---
const filmSrc = await page.getAttribute("figure.film video source", "src");
filmSrc === "/strata/the-cipher-couldnt-hide/film.mp4"
  ? ok("companion film embedded (film.mp4)") : bad(`film source is ${filmSrc}`);

// --- §2 collapse + Friedman + Kasiski, against the artifact ---
T("plaintext IC", await page.locator("#s-plain").innerText(), artifact.ic.plaintext);
T("whole-ciphertext IC", await page.locator("#s-cipher").innerText(), artifact.ic.ciphertext);
T("Friedman estimate L̂", await page.locator("#s-friedman").innerText(), artifact.break.friedmanEstimate, 0.01);

const kasiski = await page.locator("#s-kasiski").innerText();
new RegExp(`${artifact.break.kasiskiGaps}\\b`).test(kasiski) &&
  new RegExp(artifact.break.kasiskiVotesForTrueLength.replace("/", " of ")).test(kasiski)
  ? ok(`Kasiski gaps printed: "${kasiski}" (artifact ${artifact.break.kasiskiGaps}, ${artifact.break.kasiskiVotesForTrueLength})`)
  : bad(`Kasiski text "${kasiski}" disagrees with artifact ${artifact.break.kasiskiGaps} / ${artifact.break.kasiskiVotesForTrueLength}`);

// --- the coset scan: every bar's number == artifact.cosetMeanIC[L] ---
let scanOK = true;
for (let L = 1; L <= 16; L++) {
  const txt = await page.locator(`#scan .scanrow:nth-child(${L}) .reads`).innerText();
  const printed = num(txt);
  const want = artifact.break.cosetMeanIC[String(L)];
  if (Math.abs(printed - want) > 5e-5) { scanOK = false; bad(`coset L=${L}: printed ${printed}, artifact ${want}`); }
}
if (scanOK) ok("coset-IC scan: all 16 bars match artifact.cosetMeanIC to 5e-5");

// the true length must read English, its neighbours below must not (the signature)
const reads8 = await page.locator("#scan .scanrow:nth-child(8) .reads").getAttribute("class");
const reads16 = await page.locator("#scan .scanrow:nth-child(16) .reads").getAttribute("class");
const reads7 = await page.locator("#scan .scanrow:nth-child(7) .reads").getAttribute("class");
reads8.includes("english") && reads16.includes("english") && !reads7.includes("english")
  ? ok(`signature: L=8 & L=16 read English, L=7 does not (smallest English-like = ${artifact.break.smallestEnglishLikeCosetLength})`)
  : bad(`signature wrong: L8=${reads8}, L16=${reads16}, L7=${reads7}`);

// --- §3 recovered key + exact decryption ---
const recKey = (await page.locator("#r-key").innerText()).trim();
recKey === artifact.break.recoveredKey
  ? ok(`recovered key printed "${recKey}" == artifact "${artifact.break.recoveredKey}"`)
  : bad(`recovered key "${recKey}" != artifact "${artifact.break.recoveredKey}"`);

const exactTxt = (await page.locator("#r-exact").innerText()).toLowerCase();
(exactTxt.includes("exact") || exactTxt.includes("yes")) === artifact.break.decryptionExact
  ? ok(`decryption-exact flag matches artifact (${artifact.break.decryptionExact})`)
  : bad(`decryption-exact "${exactTxt}" vs artifact ${artifact.break.decryptionExact}`);

// --- interaction: stepping the key columns shows 8 distinct cells spelling the key ---
const keyCells = await page.locator("#keystrip .keycell .ltr").allInnerTexts();
keyCells.join("") === artifact.break.recoveredKey
  ? ok(`key strip spells ${keyCells.join("")} across ${keyCells.length} columns`)
  : bad(`key strip spells ${keyCells.join("")}`);

// clicking a column re-renders its χ² and the winning row is highlighted
await page.click("#keystrip .keycell:nth-child(2)");
await page.waitForTimeout(80);
const colCur = (await page.locator("#col-cur").innerText()).trim();
const winCount = await page.locator("#chi .chirow.win").count();
colCur === "2" && winCount === 1
  ? ok("clicking column 2 re-renders χ² with exactly one winning shift")
  : bad(`column step: col-cur=${colCur}, winning rows=${winCount}`);

// dragging the key-length slider updates the live readout
await page.fill("#Lslider", "16").catch(() => {});
await page.locator("#Lslider").evaluate((el) => { el.value = "16"; el.dispatchEvent(new Event("input")); });
await page.waitForTimeout(80);
const lval = (await page.locator("#Lval").innerText()).trim();
lval === "16" ? ok("key-length slider drives the live readout (L=16)") : bad(`slider readout L=${lval}`);

// --- substitution-invariance toggle keeps the plaintext IC fixed ---
await page.click("#btn-sub");
await page.waitForTimeout(80);
const subState = await page.locator("#sub-state").innerText();
const subMatch = subState.match(/\(([\d.]+)\s*=\s*([\d.]+)\)/);
subMatch && subMatch[1] === subMatch[2] && Math.abs(num(subMatch[1]) - artifact.ic.plaintext) <= 5e-5
  ? ok(`substitution toggle: IC unchanged (${subMatch[1]} = ${subMatch[2]}, == plaintext IC)`)
  : bad(`substitution invariance text: "${subState}"`);

errors.length === 0 ? ok("no console / page errors") : bad("console errors: " + errors.join(" | "));

await browser.close();
server.close();
console.log(`\n${fail === 0 ? "\x1b[32m" : "\x1b[31m"}page-driver: ${fail === 0 ? "ALL PASS" : fail + " FAILED"}\x1b[0m\n`);
process.exit(fail === 0 ? 0 : 1);
