// verify-on-contact.mjs — drive the immersive "On Contact" page in a real headless
// browser: no JS errors, the stratigraphy and curve chart render, the term picker and
// row clicks switch the chart, the verbatim figures match the extractor, and no
// horizontal overflow at phone / tablet / desktop widths.
//   npm run build && node verify-on-contact.mjs
//
// TWO GROUND TRUTHS, AND KEEPING THEM APART IS THE WHOLE JOB HERE (2026-07-31).
// This page is a DATED SNAPSHOT (2026-06-19) that has outlived two of its own premises,
// and it now carries both layers on purpose: the frozen run it renders, and the
// re-measured facts that expired underneath it. Until today this file checked the frozen
// half against a LIVE extractor run, so it asserted the page displayed today's git span
// and today's layer count. The page does not, must not, and says so in the sentence right
// beside the figure ("at the snapshot"). Seven checks were failing for asserting that the
// page had been silently restated in today's numbers, which is the one thing this layer
// promises never to do. So:
//   SNAP  research/lineage-lexicon/page.json — the frozen 2026-06-19 artifact the page
//         says it inlines verbatim. Checked to be verbatim, against the file, so the
//         comparison is page-vs-artifact and not the page agreeing with itself.
//   D     a fresh `extract.mjs --page` — today's ground, which the "premise expired"
//         boxes state and which the page must keep current.
// Resolve playwright portably, the same way scripts/headless-check.mjs does: the repo's
// own node_modules first, then the globally installed copy. A bare import fails with
// ERR_MODULE_NOT_FOUND on a fresh ephemeral VM, where playwright is installed globally,
// which is how this verifier came to be un-runnable there (found 2026-08-01).
let pw;
try { pw = (await import('playwright')).default; }
catch { pw = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default; }
const { chromium } = pw;
import { createServer } from 'http';
import { readFileSync, readdirSync, existsSync } from 'fs';
import { extname, join } from 'path';
import { execSync } from 'child_process';
import { fileURLToPath as __f2p } from 'url';
import { dirname as __dn } from 'path';
const AW_REPO_ROOT = __dn(__f2p(import.meta.url));

const root = AW_REPO_ROOT + '/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(8143,r));
const URL_ = 'http://localhost:8143/strata/on-contact/';

// A shallow clone (what every ephemeral cloud session gets) truncates git history, so
// every figure derived FROM THE LOG is wrong here through no fault of the page. Detect
// that and skip those two checks with a stated reason rather than printing a false red,
// which is exactly what this file did on 2026-08-01 before the guard was added.
const SHALLOW = existsSync(join(AW_REPO_ROOT, '.git', 'shallow'));
if (SHALLOW) console.log(`\n  note  shallow clone (${execSync('git rev-list --count HEAD', { cwd: AW_REPO_ROOT, encoding:'utf8' }).trim()} commits): the two git-derived checks are SKIPPED, not passed.\n        Fix it rather than living with it, it is one command: git fetch --unshallow origin\n`);

// ground truth from the extractor, run now, against the live corpus
const D = JSON.parse(execSync('node research/lineage-lexicon/extract.mjs --page', { cwd: AW_REPO_ROOT, encoding:'utf8' }));
const rm = D.terms.find(t=>t.term==='register mirror');
// ground truth for the frozen half: the committed snapshot artifact, not the page
const SNAP = JSON.parse(readFileSync(join(AW_REPO_ROOT, 'research/lineage-lexicon/page.json'), 'utf8'));
const snapRm = SNAP.terms.find(t=>t.term==='register mirror');

// An independent recount of which published layers carry the phrase, done here from the
// strata themselves rather than read off the extractor, so the two can disagree.
const strataDir = join(AW_REPO_ROOT, 'src/content/strata');
const rmStrata = readdirSync(strataDir).filter(f=>f.endsWith('.md')).map(f=>{
  const src = readFileSync(join(strataDir, f), 'utf8');
  return { slug: f.replace(/\.md$/,''), has: /register mirror/i.test(src), seam: (src.match(/^seam:\s*"?([\w-]+)"?/m)||[])[1] || null };
}).filter(s=>s.has);

let fails = 0; const ok=(n,c,x='')=>{ if(!c)fails++; console.log(`${c?'  ok':'FAIL'}  ${n}${x?'   '+x:''}`); };
let pageData = null;   // the blob the served page actually carries, read out of the browser
let pageBody = null;   // its rendered text, kept for the checks that are not per-viewport

const browser = await chromium.launch();
for (const [label, w, h] of [['phone',390,844],['tablet',768,1024],['desktop',1280,900]]) {
  const ctx = await browser.newContext({ viewport:{width:w,height:h} });
  const page = await ctx.newPage();
  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(`[${label}] no JS errors`, errs.length===0, errs.slice(0,2).join(' | '));
  if (!pageData) pageData = await page.evaluate(()=>JSON.parse(JSON.stringify(DATA)));

  // stratigraphy rows = one per term
  const rows = await page.$$eval('.srow', els=>els.map(e=>e.dataset.term));
  ok(`[${label}] stratigraphy has all ${D.terms.length} terms`, rows.length===D.terms.length, `got ${rows.length}`);

  // chart renders paths (default register mirror -> at least the session curve)
  const paths = await page.$$eval('#chart path', els=>els.length);
  ok(`[${label}] curve chart drew paths`, paths>=1, `paths=${paths}`);

  // default selection is register mirror; gloss mentions the diffusion line
  const gloss = await page.$eval('#chtitle', e=>e.textContent);
  ok(`[${label}] default gloss names register mirror`, /register mirror/.test(gloss));
  ok(`[${label}] gloss names the console.log engine`, /tool began printing/.test(gloss));

  // click the 'seam' picker button -> chart switches, gloss updates to seam + crystalline
  await page.click('.pick button:has-text("seam")');
  const g2 = await page.$eval('#chtitle', e=>e.textContent);
  ok(`[${label}] selecting seam updates gloss`, /^seam/.test(g2.trim()) || /\bseam\b/.test(g2.slice(0,40)));
  const sel = await page.$$eval('.srow.sel', els=>els.map(e=>e.dataset.term));
  ok(`[${label}] row highlight follows selection`, sel.length===1 && sel[0]==='seam', sel.join(','));

  // ---- the frozen half: the page must render the SNAPSHOT, and label it as one ----
  const body = await page.$eval('body', e=>e.innerText);
  if (!pageBody) pageBody = body;
  ok(`[${label}] shows the snapshot's git span, marked as the snapshot's`,
    body.includes(`${SNAP.git.spanDays} day`) && /at the snapshot/i.test(body),
    `snapshot span ${SNAP.git.spanDays}d`);
  ok(`[${label}] shows the snapshot's layer + session counts`,
    body.includes(String(SNAP.corpora.strata.layers)) && body.includes(String(SNAP.corpora.sessions.count)),
    `${SNAP.corpora.strata.layers} layers / ${SNAP.corpora.sessions.count} sessions`);
  ok(`[${label}] shows 43/43 checks`, body.includes('43/43'));

  // ---- the live half: the "premise expired" box must state today's ground ----
  // The commit-day count in that box is ANCHORED to the day it was re-measured, and an
  // anchored figure does not rot, so comparing it to today's live count would manufacture
  // a red the morning after it was written. It is still checkable exactly: re-derive it
  // from the log AT ITS OWN ANCHOR, with the anchor read off the page rather than typed
  // in here. The layer count beside it is not anchored (it is stated in the present tense,
  // and it cannot move unless a layer is backdated), so that one is checked live.
  const box = await page.$eval('.expired', e=>e.innerText);
  const anchored = box.match(/Re-measured on (\d{4}-\d{2}-\d{2}),[\s\S]{0,80}?(\d[\d,]*) distinct commit days/);
  ok(`[${label}] the expired-premise box gives its commit-day count with an anchor date`,
    !!anchored, anchored ? `${anchored[2]} days as of ${anchored[1]}` : box.slice(0, 90));
  const daysAsOf = anchored
    ? new Set(execSync(`git log --pretty=format:%cI --until=${anchored[1]}T23:59:59`, { cwd: AW_REPO_ROOT, encoding:'utf8' })
        .trim().split('\n').map(s=>s.slice(0,10))).size
    : null;
  if (SHALLOW) {
    console.log(`  skip  [${label}] the two git-derived premise checks (shallow clone truncates the log)`);
  } else {
    ok(`[${label}] ...and that count re-derives from the log at that date`,
      !!anchored && Number(anchored[2].replace(/,/g,'')) === daysAsOf,
      anchored ? `page ${anchored[2]} vs git ${daysAsOf}` : 'no anchor to check');
    ok(`[${label}] the surviving premise carries the live pre-repository layer count`,
      box.includes(`${D.preRepoStrata} layers`), `live preRepoStrata=${D.preRepoStrata}`);
  }

  // no horizontal overflow
  const overflow = await page.evaluate(()=> document.documentElement.scrollWidth - document.documentElement.clientWidth);
  ok(`[${label}] no horizontal overflow`, overflow<=1, `overflow=${overflow}px`);

  await ctx.close();
}
await browser.close(); server.close();

// the page's promise about its own data: the snapshot is inlined VERBATIM. Checked against
// the committed artifact, so this is page-vs-file and not the page agreeing with itself.
ok('the page inlines the snapshot artifact verbatim',
  JSON.stringify(pageData)===JSON.stringify(SNAP),
  `page ${JSON.stringify(pageData).length}B vs artifact ${JSON.stringify(SNAP).length}B`);

// ---- the headline exception, which has since crossed the stage ----
// Until 2026-07-31 this was one line: `ok('register mirror absent from strata',
// rm.strataTotal===0)`. That was the page's sharpest claim — the word the reader never
// sees — and it was true on the evening the snapshot was taken. It is not true now, and
// the way it stopped being true is the best thing that has happened to this layer: the
// word entered the published strata on 2026-06-20, the DAY AFTER this snapshot, in
// lineage-seam-drift, the sequel study of this same creole, which names it as an object
// of study exactly the way this layer does. Frontstage it has still never been USED, only
// mentioned, and only by the studies that measure it. So the claim splits in two and both
// halves are asserted; dropping the check to stay green would have buried the finding.
ok('register mirror was strata-absent in the snapshot the page renders',
  snapRm.strataTotal===0, `snapshot strataTotal=${snapRm.strataTotal}`);
ok('register mirror has since surfaced in the published strata',
  rm.strataTotal>0 && !!rm.firstStratum, `strataTotal=${rm.strataTotal}, first=${rm.firstStratum && rm.firstStratum.slug}`);
ok('...and every layer that carries it is in the lineage seam (the studies of the creole)',
  rmStrata.length>0 && rmStrata.every(s=>s.seam==='lineage'),
  rmStrata.map(s=>`${s.slug}[${s.seam}]`).join(' '));
ok('...and that recount agrees with the extractor, self-exclusion included',
  rmStrata.filter(s=>s.slug!==D.corpora.strata.selfExcluded).length === rm.strataTotal,
  `recount ${rmStrata.filter(s=>s.slug!==D.corpora.strata.selfExcluded).length} vs extractor ${rm.strataTotal}`);
ok('the page names the layer and the date the crossing happened',
  !!rm.firstStratum && !!pageBody && pageBody.includes(rm.firstStratum.date) && pageBody.includes(rm.firstStratum.title),
  rm.firstStratum ? `${rm.firstStratum.date} ${rm.firstStratum.title}` : 'no first stratum');
ok('register mirror first appears on/after 2026-06-14', rm.firstOutDate>='2026-06-14', rm.firstOutDate);

// ---- the two premises, as directions rather than frozen numbers ----
ok('the premise the page retired really has expired (git is no longer one day)',
  D.git.uniqueDays>1 && D.git.spanDays>1, `${D.git.uniqueDays} commit days over ${D.git.spanDays}d`);
ok('the premise it kept still holds (the corpus predates its repository)',
  D.preRepoStrata>0 && D.contentSpanDays>D.git.spanDays,
  `${D.preRepoStrata} pre-repo layers; content ${D.contentSpanDays}d vs git ${D.git.spanDays}d`);

console.log(`\n${fails===0?'✓ all checks passed':'✗ '+fails+' FAILED'}`);
process.exit(fails===0?0:1);
