#!/usr/bin/env node
// verify-no-closer-than-the-first-day.mjs — the browser lane for
// /strata/no-closer-than-the-first-day/.
//
// research/lineage-crowding/verify.mjs settles the ANALYSIS: it recomputes every figure
// from the repository and asserts 36 things about it, including four controls that assert
// the instrument's artefacts are real. It cannot see the page.
//
// This one opens the page in a real browser and drives it, because the page's whole claim
// is that a reader can operate the measurement and watch the answer move. A page whose
// ladder does not move is not a showing, it is a picture of one. Every number asserted
// here is read off the rendered DOM and compared against the committed artifact, so if the
// page ever renders figures that are not the analysis's own figures, this goes red.
//
//   node verify-no-closer-than-the-first-day.mjs                # builds nothing; needs a served build
//   BASE=http://127.0.0.1:8811 node verify-no-closer-than-the-first-day.mjs
//
// Requires a local server over `dist/` (npm run build && npx http-server dist -p 8811).

import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';

const BASE = process.env.BASE || 'http://127.0.0.1:8811';
const URL_ = BASE + '/strata/no-closer-than-the-first-day/';
const ART = JSON.parse(readFileSync(new URL('./research/lineage-crowding/page.json', import.meta.url), 'utf8'));

let pass = 0, fail = 0;
const ok = (c, m, d = '') => {
  if (c) { pass++; console.log('  \x1b[32m✓\x1b[0m ' + m + (d ? '  ' + d : '')); }
  else { fail++; console.log('  \x1b[31m✗ ' + m + (d ? '  ' + d : '') + '\x1b[0m'); }
};

// Playwright is installed at a path that varies between the local box and a cloud VM, so
// try the bare specifier first and fall back. This is the house pattern; three verifiers
// died silently on a hardcoded absolute path before it was written down.
let chromium;
try { ({ chromium } = await import('playwright')); }
catch { ({ chromium } = createRequire('/opt/node22/lib/node_modules/x.js')('playwright')); }

const browser = await chromium.launch();
const errors = [];

async function open(width, height) {
  const page = await browser.newPage({ viewport: { width, height } });
  page.on('pageerror', (e) => errors.push(width + 'px: ' + e.message));
  page.on('console', (m) => { if (m.type() === 'error') errors.push(width + 'px console: ' + m.text()); });
  await page.goto(URL_, { waitUntil: 'domcontentloaded' });
  await page.waitForTimeout(700);
  return page;
}

const page = await open(1440, 900);

console.log('\nA. the page renders the analysis, not a copy of it');
const inlined = await page.evaluate(() => JSON.parse(document.getElementById('data').textContent));
ok(inlined.corpus.layers === ART.corpus.layers && inlined.ladder.prose[3].isoCorr === ART.ladder.prose[3].isoCorr,
  'the inlined data block is the committed artifact', `${inlined.corpus.layers} layers`);
const shown = await page.evaluate(() => {
  const g = (s) => (document.querySelector(s) || {}).textContent || '';
  return { readout: g('#ladder-readout'), verdict: g('#ladder-verdict'), pred: g('#pred-verdict') };
});
ok(/[-+−]?0\.16/.test(shown.readout), 'the ladder opens on rung P0 and prints its correlation', shown.readout.trim());
ok(shown.verdict.indexOf('Outside the null band') === 0, 'and says plainly whether that is outside the null', shown.verdict.slice(0, 40));

console.log('\nB. the ladder actually moves when a reader climbs it');
const climbed = [];
for (let i = 0; i < 4; i++) {
  await page.click('#rungs .rung >> nth=' + i);
  await page.waitForTimeout(120);
  climbed.push(await page.evaluate(() => document.getElementById('ladder-readout').textContent.trim()));
}
const nums = climbed.map((s) => Number(s.replace(/[^0-9.\-]/g, '')) * (s.indexOf('−') >= 0 ? -1 : 1));
ok(new Set(climbed).size === 4, 'all four prose rungs print different correlations', climbed.join(' · '));
ok(Math.abs(nums[3] - ART.ladder.prose[3].isoCorr) < 0.0006,
  'and the top rung prints the artifact\'s own top-rung figure', `${nums[3]} vs ${ART.ladder.prose[3].isoCorr}`);
const dots = await page.evaluate(() => document.querySelectorAll('#scatter circle.dot').length);
ok(dots === ART.corpus.layers, 'the scatter plots every layer in the corpus', `${dots}`);

await page.click('#inst-meta');
await page.waitForTimeout(150);
const metaRungs = await page.evaluate(() => document.querySelectorAll('#rungs .rung').length);
const metaFirst = await page.evaluate(() => document.getElementById('ladder-readout').textContent.trim());
ok(metaRungs === 3, 'switching instruments switches the ladder to the metadata rungs', `${metaRungs} rungs`);
ok(/0\.3[34]/.test(metaFirst), 'whose first rung is the large uncentred trend', metaFirst);
await page.click('#rungs .rung >> nth=1');
await page.waitForTimeout(150);
const metaCentred = await page.evaluate(() => ({
  r: document.getElementById('ladder-readout').textContent.trim(),
  v: document.getElementById('ladder-verdict').textContent.trim(),
}));
ok(/0\.01/.test(metaCentred.r) && /Inside the null band/.test(metaCentred.v),
  'and centring the space drops it inside the null band, in front of the reader',
  metaCentred.r + ' — ' + metaCentred.v.slice(0, 30));

console.log('\nC. the length demonstration is operable and moves in one direction');
const lens = [];
for (let i = 0; i <= 5; i++) {
  await page.evaluate((v) => {
    const el = document.getElementById('len');
    el.value = String(v);
    el.dispatchEvent(new Event('input', { bubbles: true }));
  }, i);
  await page.waitForTimeout(60);
  lens.push(await page.evaluate(() => document.getElementById('len-out').textContent.trim()));
}
const lenVals = lens.map((s) => Number(s.split('isolation')[1]));
ok(lenVals.every((v, i) => i === 0 || v <= lenVals[i - 1]),
  'dragging the dial to show more of the same text only ever lowers measured isolation',
  lenVals.join(' > '));
ok(Math.abs(lenVals[0] - ART.length.corpusCurve[0].meanIsolation) < 1e-9 &&
   Math.abs(lenVals[5] - ART.length.corpusCurve[5].meanIsolation) < 1e-9,
  'and the endpoints are the artifact\'s own curve', `${lenVals[0]} .. ${lenVals[5]}`);

console.log('\nD. the histogram shows the cone rather than asserting it');
const occ = [];
for (const k of ['raw', 'cen', 'pro']) {
  await page.click('#hist-' + k);
  await page.waitForTimeout(80);
  occ.push(await page.evaluate(() => ({
    bars: document.querySelectorAll('#hist rect').length,
    text: document.getElementById('hist-verdict').textContent.trim(),
  })));
}
ok(occ[0].bars <= 10 && occ[1].bars > 40,
  'the shipped embedding occupies a sliver of the cosine range and the centred one does not',
  `${occ[0].bars} bars vs ${occ[1].bars}`);
ok(/0\.9567/.test(occ[0].text), 'and the page prints the measured mean beside it', occ[0].text.slice(0, 46));

console.log('\nE. the flat line is drawn against a band that is not flat');
const predGeom = await page.evaluate(() => {
  const poly = document.querySelector('#predchart polygon');
  const lines = document.querySelectorAll('#predchart polyline');
  const pts = (n) => n.getAttribute('points').split(' ').map((p) => p.split(',').map(Number));
  const nullLine = pts(lines[0]), realLine = pts(lines[1]);
  // y grows downward, so "real is above the null" on the page means a SMALLER y.
  const n = Math.min(nullLine.length, realLine.length), h = Math.floor(n / 2);
  let earlyUnder = 0, lateOver = 0;
  for (let i = 0; i < h; i++) if (realLine[i][1] > nullLine[i][1]) earlyUnder++;
  for (let i = h; i < n; i++) if (realLine[i][1] < nullLine[i][1]) lateOver++;
  return {
    hasBand: !!poly,
    nullRise: nullLine[nullLine.length - 1][1] - nullLine[0][1],
    points: n, half: h, earlyUnder, lateOver,
    dots: document.querySelectorAll('#predchart circle').length,
  };
});
const shownPred = await page.evaluate(() => document.getElementById('pred-verdict').textContent);
ok(predGeom.hasBand, 'the shuffled-calendar band is drawn as an area, not described in words');
// y grows downward in SVG, so a falling curve has a POSITIVE rise here.
ok(predGeom.nullRise > 40, 'the null curve visibly falls across the chart', `${predGeom.nullRise.toFixed(0)}px down`);
// The finding is the CROSSING, not flatness: the real curve starts inside/below the band
// and ends above it. Asserting "does not fall" would have been false, and this check said so.
// "Crossing" is a claim about the SWING, so measure the swing rather than pick a threshold
// on either end. The share of points drawn under the shuffled mean must fall sharply between
// the first half of the chart and the second. A curve that never crossed would swing by ~0.
{
  const lateN = predGeom.points - predGeom.half;
  const earlyShare = predGeom.earlyUnder / predGeom.half;
  const lateShare = (lateN - predGeom.lateOver) / lateN;
  ok(earlyShare > 0.6 && lateShare < 0.4 && earlyShare - lateShare > 0.3,
    'while the share of the real curve drawn UNDER the shuffled mean swings hard between the halves, which is the crossing',
    `${(earlyShare * 100).toFixed(0)}% under early, ${(lateShare * 100).toFixed(0)}% under late, ` +
    `a swing of ${((earlyShare - lateShare) * 100).toFixed(0)} points`);
}
ok(/starts below the band/.test(shownPred) && /ends above it/.test(shownPred),
  'and the page says so in words a reader can check against the picture',
  shownPred.slice(shownPred.indexOf('The amber'), shownPred.indexOf('The amber') + 74));
ok(predGeom.dots === ART.corpus.layers - 1, 'every layer but the first is plotted', `${predGeom.dots}`);

console.log('\nF. the tables are the artifact\'s own rows');
const rows = await page.evaluate(() => ({
  pairs: [...document.querySelectorAll('#pairs tbody tr')].map((r) => r.cells[0].textContent.trim()),
  eras: document.querySelectorAll('#eras tbody tr').length,
  firstPair: (document.querySelector('#pairs tbody tr a') || {}).getAttribute
    ? document.querySelector('#pairs tbody tr a').getAttribute('href') : '',
}));
ok(rows.pairs.length === ART.closestPairs.length, 'every closest pair is listed', `${rows.pairs.length}`);
ok(rows.firstPair === '/strata/' + ART.closestPairs[0].a + '/',
  'and each one links to the layer it names, so a reader can go and look', rows.firstPair);
ok(rows.eras === ART.eras.length, 'every era row is listed', `${rows.eras}`);

console.log('\nG. it survives the shapes a reader will actually use');
await page.close();
for (const w of [390, 768, 1440]) {
  const p = await open(w, 900);
  const over = await p.evaluate(() => ({
    doc: document.documentElement.scrollWidth,
    win: window.innerWidth,
    dots: document.querySelectorAll('#scatter circle.dot').length,
    bars: document.querySelectorAll('#hist rect').length,
  }));
  ok(over.doc <= over.win + 1, `no horizontal overflow at ${w}px`, `${over.doc} vs ${over.win}`);
  ok(over.dots > 0 && over.bars > 0, `every chart still draws at ${w}px`, `${over.dots} dots, ${over.bars} bars`);
  await p.close();
}
ok(errors.length === 0, 'and throws nothing while doing any of it', errors.slice(0, 3).join(' | '));

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