#!/usr/bin/env node
/* Headless-browser check for /strata/gardens-of-eden/.
   Serves public/ statically and drives the page: the census strip's live-computed
   Garden-of-Eden counts match an independent Node recomputation; the orphan hunter
   correctly labels a known orphan a Garden of Eden and a known non-orphan as having a
   predecessor that steps to it; the live brute-vs-transfer check reports agreement;
   reversible rules show all zeros; no JS errors; no horizontal overflow at 390/768/1440.
   Run: node verify-gardens-of-eden.mjs */
import http from 'node:http';
import { readFile } from 'node:fs/promises';
import { existsSync, statSync } from 'node:fs';
import { join, extname } from 'node:path';
import { goeSizes, bruteImageGoE, step } from './research/ca-garden-of-eden/engine.mjs';
import pkg from '/opt/node22/lib/node_modules/playwright/index.js';
const { chromium } = pkg;

const ROOT = new URL('.', import.meta.url).pathname;
const T = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'font/woff2', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.json': 'application/json' };
const server = http.createServer(async (req, res) => {
  let p = decodeURIComponent(req.url.split('?')[0]);
  if (p.endsWith('/')) p += 'index.html';
  const fp = join(ROOT, 'public', p);
  if (!existsSync(fp) || !statSync(fp).isFile()) { res.writeHead(404); res.end('nf'); return; }
  res.writeHead(200, { 'content-type': T[extname(fp)] || 'application/octet-stream' });
  res.end(await readFile(fp));
});
await new Promise(r => server.listen(0, r));
const base = 'http://localhost:' + server.address().port;

const browser = await chromium.launch();
let pass = 0, fail = 0;
const ok = (cond, label) => { if (cond) { pass++; console.log('  ok   ' + label); } else { fail++; console.error('  FAIL ' + label); } };
const errors = [];

const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.on('pageerror', e => errors.push(String(e.message)));
page.on('console', m => { if (m.type() === 'error') errors.push(m.text()); });
await page.goto(base + '/strata/gardens-of-eden/', { waitUntil: 'networkidle' });

// --- census strip matches Node ground truth (rule 30 default) ---
async function stripValues() {
  return await page.$$eval('#cen-strip .seqcell .v', els => els.map(e => e.textContent.trim()));
}
{
  const vals = await stripValues();
  const gt = goeSizes(30, vals.length).slice(1).map(String);
  ok(vals.length >= 24, `census strip renders ${vals.length} terms`);
  ok(JSON.stringify(vals) === JSON.stringify(gt), 'census strip == Node goeSizes(rule 30)');
}
// switch census to rule 170 (reversible) -> all zeros
{
  await page.selectOption('#cen-rule', '170');
  const vals = await stripValues();
  ok(vals.every(v => v === '0'), 'reversible rule 170: census all zeros');
  await page.selectOption('#cen-rule', '30');
}

// --- orphan hunter: known orphan vs known non-orphan ---
async function setTodayRing(bitmask, n) {
  await page.$$eval('#hunt-today .cell', (els, mask) => {
    els.forEach((el, i) => {
      const want = (mask >> i) & 1;
      const cur = el.getAttribute('aria-pressed') === 'true' ? 1 : 0;
      if (want !== cur) el.click();
    });
  }, bitmask);
}
{
  const n = 11, rule = 30;
  // ensure slider/rule set
  await page.selectOption('#hunt-rule', String(rule));
  await page.evaluate(() => { const s = document.getElementById('hunt-n'); s.value = '11'; s.dispatchEvent(new Event('input', { bubbles: true })); });

  // find a known orphan and a known non-orphan in Node
  const total = 1 << n; const img = new Set();
  for (let x = 0; x < total; x++) img.add(step(rule, n, x));
  let orphan = -1, nonorphan = -1;
  for (let y = 0; y < total; y++) { if (!img.has(y) && orphan < 0) orphan = y; if (img.has(y) && nonorphan < 0) nonorphan = y; }
  ok(orphan >= 0, `Node: rule 30 n=11 has an orphan (y=${orphan})`);

  await setTodayRing(orphan, n);
  const v1 = await page.textContent('#hunt-verdict');
  ok(/GARDEN OF EDEN/.test(v1), `orphan y=${orphan} labelled a Garden of Eden`);

  await setTodayRing(nonorphan, n);
  const v2 = await page.textContent('#hunt-verdict');
  ok(/has a yesterday/.test(v2), `non-orphan y=${nonorphan} labelled has-a-yesterday`);

  // the yesterday ring must actually step to today
  const yestBits = await page.$$eval('#hunt-yesterday .cell', els => els.reduce((m, e, i) => m | ((e.getAttribute('aria-pressed') === 'true' ? 1 : 0) << i), 0));
  ok(step(rule, n, yestBits) === nonorphan, 'displayed yesterday steps to today under the rule');

  // live brute-vs-transfer check line reports agreement, and the count matches Node
  const cl = await page.textContent('#check-live');
  ok(/they agree/.test(cl), 'live check line reports brute==transfer agreement');
  const bruteGoe = bruteImageGoE(rule, n).goe;
  ok(cl.includes(String(bruteGoe)), `live check count == Node brute GoE (${bruteGoe})`);
}

// --- no JS errors ---
ok(errors.length === 0, 'no JS console/page errors' + (errors.length ? ' :: ' + errors.slice(0, 3).join(' | ') : ''));

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

await browser.close();
server.close();
console.log(`\n${pass}/${pass + fail} checks passed`);
process.exit(fail ? 1 : 0);
