#!/usr/bin/env node
// verify.mjs — sweep entry point for research/lineage-crowding.
//
// The real checks live in extract.mjs --verify (36 assertions across the corpus
// definition, the anisotropy of the shipped embedding, the length artefact, every rung of
// the control ladder and its date-shuffle null, and the surviving result). This shim
// exists because research/_sweep/sweep.mjs discovers only files named verify.mjs.
//
// Offline, zero dependency, deterministic. It also checks the one thing extract.mjs
// cannot check about itself: that the committed artifact and the shipped page still carry
// the same numbers the assertions were written against.

import { execFileSync } from 'node:child_process';
import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const PAGE = join(ROOT, 'public', 'strata', 'no-closer-than-the-first-day', 'index.html');
const ARTIFACT = join(HERE, 'page.json');

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

let analysisFailed = false;
try {
  execFileSync(process.execPath, ['--max-old-space-size=8192', join(HERE, 'extract.mjs'), '--verify'], { stdio: 'inherit' });
} catch (e) {
  analysisFailed = true;
  console.log('\n  (extract.mjs --verify exited ' + (e.status || 1) + ')');
}

console.log('\nH. the page and the artifact have not drifted apart');
const artifactExists = existsSync(ARTIFACT);
ok(artifactExists, 'the committed artifact is present', 'research/lineage-crowding/page.json');
if (artifactExists && existsSync(PAGE)) {
  const html = readFileSync(PAGE, 'utf8');
  const TAG = '<script id="data" type="application/json">';
  const i = html.indexOf(TAG);
  ok(i >= 0, 'the shipped page carries an inlined data block the gate can find');
  if (i >= 0) {
    const inlined = html.slice(i + TAG.length, html.indexOf('</script>', i));
    let same = false, why = '';
    try {
      same = JSON.stringify(JSON.parse(inlined)) === JSON.stringify(JSON.parse(readFileSync(ARTIFACT, 'utf8')));
    } catch (e) { why = String(e.message).slice(0, 80); }
    ok(same, 'and it is the committed artifact, figure for figure', why);
  }
  // The page states several figures in its own prose rather than through the data block.
  // Those are the ones that can rot silently, so they are named here.
  const art = JSON.parse(readFileSync(ARTIFACT, 'utf8'));
  // The count is read from the analysis rather than typed here, so this cannot drift into
  // agreeing with a stale page. extract.mjs prints its own tally on the last line.
  const tally = execFileSync(process.execPath, ['--max-old-space-size=8192', join(HERE, 'extract.mjs'), '--verify'], { encoding: 'utf8' })
    .trim().split('\n').pop().match(/(\d+) checks/);
  const n = tally ? tally[1] : '?';
  ok(html.includes('<b>' + n + ' checks</b>'),
    'the page claims the number of analysis checks that actually run', n);
  ok(html.includes('400 words'), 'the page names the word budget the analysis used', String(art.corpus.wordFloor));
  ok(art.corpus.layers === art.layers.length,
    'the artifact\'s layer list is the same length as the corpus it reports', `${art.corpus.layers}`);
  ok(art.series.P3.length === art.corpus.layers && art.series.M1.length === art.corpus.layers,
    'every plotted series covers every layer', `${art.series.P3.length}`);
  ok(art.predecessor.prose.series.length === art.corpus.layers - 1,
    'and the nearest-predecessor series covers every layer but the first, which had no predecessor',
    `${art.predecessor.prose.series.length}`);
} else {
  ok(false, 'the shipped page exists', PAGE);
}

console.log(`\n${pass + fail} page checks · ${pass} pass · ${fail} fail`);
process.exit(fail === 0 && !analysisFailed ? 0 : 1);
