#!/usr/bin/env node
// Verifier for /strata/nothing-here-is-a-bug/.
//
// Three jobs. (1) Re-run the controls here and insist they still agree, because
// the divided rows mean nothing if the instrument cannot come back clean.
// (2) Recount the capture from its own rows rather than trusting the counters it
// wrote. (3) Read the SHIPPED page and check its headline counts (in the prose
// and the meta descriptions) and the Node versions it names against the capture,
// that the battery the browser runs is byte-identical to battery.mjs, and that the
// probe code in it is the code the runtimes ran. (Until 2026-10-18 this said
// "every figure in its prose"; it never read every figure.)
//
//   node research/correct-is-not-determined/verify-nothing-here-is-a-bug.mjs

import { readFileSync, existsSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { PROBES, runBattery } from './battery.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const REPO = join(HERE, '..', '..');
const PUB = join(REPO, 'public', 'strata', 'nothing-here-is-a-bug');

let pass = 0, fail = 0;
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  ✗ ${name}  ${detail}`); }
};

console.log('\nverify nothing-here-is-a-bug\n');

const cap = JSON.parse(readFileSync(join(HERE, 'data', 'capture.json'), 'utf8'));

// ---------------------------------------------------------------------------
// 1. The controls, run again now, in this process
// ---------------------------------------------------------------------------
console.log('the controls, re-run here');
{
  const mine = runBattery();
  const controls = PROBES.filter((p) => p.kind === 'determined');
  ok('there are controls at all', controls.length >= 3, `${controls.length}`);
  for (const c of controls) {
    const captured = cap.rows.find((r) => r.id === c.id);
    const values = Object.values(captured.answers).filter((v) => v !== 'not a browser');
    const allSame = new Set(values).size === 1;
    const matchesNow = values[0] === mine[c.id];
    ok(`${c.id} agrees across every captured runtime, and here`, allSame && matchesNow,
      `${JSON.stringify(mine[c.id])}`);
  }
  // The instrument must be able to say "divided". If it never can, the zero
  // above is not evidence of anything.
  const anyDivided = cap.rows.some((r) => r.divided);
  ok('the instrument CAN report a division (it did, below)', anyDivided);
}

// ---------------------------------------------------------------------------
// 2. Recount the capture from its rows
// ---------------------------------------------------------------------------
console.log('\nthe counts, recomputed from the rows');
{
  let divided = 0, agreed = 0, controls = 0, controlsDivided = 0;
  for (const r of cap.rows) {
    const usable = Object.values(r.answers)
      .filter((a) => a !== 'not a browser' && !String(a).startsWith('threw:'));
    if (usable.length < 2) continue;
    const isDivided = new Set(usable).size > 1;
    if (r.kind === 'determined') { controls++; if (isDivided) controlsDivided++; }
    else if (isDivided) divided++; else agreed++;
    ok(`row ${r.id} carries the divided flag it earns`, r.divided === isDivided, '');
  }
  ok('divided count', divided === cap.divided, `${divided}`);
  ok('agreed count', agreed === cap.agreed, `${agreed}`);
  ok('comparable count', divided + agreed === cap.comparable, `${divided + agreed}`);
  ok('control count', controls === cap.controls, `${controls}`);
  ok('no control divided', controlsDivided === 0 && cap.controlsDivided === 0);
  ok('every probe in the battery has a row', PROBES.length === cap.rows.length,
    `${PROBES.length} probes, ${cap.rows.length} rows`);
  ok('two distinct engine families were measured',
    new Set(cap.runtimes.map((r) => r.engine.replace(' (in a browser)', ''))).size >= 2,
    [...new Set(cap.runtimes.map((r) => r.engine))].join(', '));
}

// ---------------------------------------------------------------------------
// 3. The independent second opinion on the headline row
// ---------------------------------------------------------------------------
// The Cancun figure is the page's showpiece, so it is checked a second way:
// against the system zoneinfo through a different language's implementation,
// which shares no code with any JavaScript engine above.
console.log('\nthe headline row, checked through a non-JavaScript path');
{
  const row = cap.rows.find((r) => r.id === 'tz.cancun.1990');
  const answers = new Set(Object.values(row.answers).filter((v) => v !== 'not a browser'));
  ok('the runtimes really do disagree about it', answers.size > 1,
    [...answers].join(' against '));
  try {
    const py = execFileSync('python3', ['-c',
      "import datetime,zoneinfo;print(datetime.datetime(1990,7,15,12,tzinfo=datetime.timezone.utc)"
      + ".astimezone(zoneinfo.ZoneInfo('America/Cancun')).strftime('%H:%M'))"],
    { encoding: 'utf8' }).trim();
    ok('a third implementation (CPython over the system zoneinfo) lands on one of them',
      answers.has(py), `python3 says ${py}`);
  } catch (e) {
    ok('a third implementation could be consulted', false, e.message.split('\n')[0]);
  }
}

// ---------------------------------------------------------------------------
// 4. The shipped page
// ---------------------------------------------------------------------------
console.log('\nthe shipped page');
{
  ok('the page exists', existsSync(join(PUB, 'index.html')));
  const html = readFileSync(join(PUB, 'index.html'), 'utf8');
  const shipped = readFileSync(join(PUB, 'battery.js'), 'utf8');
  const source = readFileSync(join(HERE, 'battery.mjs'), 'utf8');
  ok('the battery the browser runs is byte-identical to battery.mjs',
    shipped === source, `${shipped.length} bytes`);
  // The clause notes in battery.mjs were corrected on 2026-10-18, after the
  // capture, and one probe's kind changed (ctl.tostring). The probes themselves
  // must not change without a new capture: this is the sha256 of every id,
  // question and run function as committed with the capture (625bead4a8c).
  const PROBE_CODE = '7f49f28c796e492ec0c54fe037d9b3be2014dce53a647325bc1365b37a09dba8';
  const code = createHash('sha256')
    .update(PROBES.map((p) => p.id + '\n' + p.question + '\n' + p.run.toString()).join('\n')).digest('hex');
  ok('the probe code is the code the captured runtimes ran', code === PROBE_CODE, code.slice(0, 12));

  const shippedCap = JSON.parse(readFileSync(join(PUB, 'capture.json'), 'utf8'));
  ok('the shipped capture matches the research capture',
    JSON.stringify(shippedCap) === JSON.stringify(cap));

  const WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
    'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'];
  const W = (n) => WORDS[n] ?? String(n);
  const cap1 = (w) => w[0].toUpperCase() + w.slice(1);
  const claims = [
    ['the probe count', String(cap.probes)],
    ['the runtime count', `${W(cap.runtimes.length)} conforming implementations`],
    ['the divided count in the meta descriptions', `${cap1(W(cap.divided))} of the ${W(cap.comparable)}`],
    ['the divided count in the body', `"${cap1(W(cap.divided))} of ${W(cap.comparable)}"`],
    ['the comparable count in the body', `these</em> ${W(cap.comparable)} questions`],
    ['the control count in the body', `${cap1(W(cap.controls))} of them are <strong>controls`],
    ['the control count in the check', `${cap1(W(cap.controls))} probes ask things the standards do determine`],
  ];
  // the Node versions the body names, against the versions captured
  for (const id of ['node21', 'node20']) {
    const rt = cap.runtimes.find((r) => r.id === id);
    claims.push([`the ${id} version in prose`, `Node ${rt ? rt.version.replace(/^v/, '') : '(not captured)'}`]);
  }
  for (const [name, needle] of claims) {
    ok(`${name} appears in the page`, html.toLowerCase().includes(needle.toLowerCase()), needle);
  }
  ok('the prose figure matches the capture: 5 divided of 19',
    cap.divided === 5 && cap.comparable === 19 && html.includes('Five of the nineteen'), `${cap.divided} of ${cap.comparable}`);
  ok('the prose figure matches the capture: 3 controls, none divided',
    cap.controls === 3 && cap.controlsDivided === 0 && html.includes('All three came'), '');
  ok('the probe count in the prose matches the battery',
    cap.probes === PROBES.length && html.includes('Twenty-four questions'), `${PROBES.length}`);

  // Every layer the portal names has to exist and be reachable. Only the spine
  // counts: the members paragraphs the portal wrote, not the nearby-layers block
  // the site's own tooling injects into every immersive page after the fact.
  const spine = [...html.matchAll(/<p class="members">([\s\S]*?)<\/p>/g)].map((m) => m[1]).join(' ');
  const linked = [...spine.matchAll(/href="\/strata\/([a-z0-9-]+)\//g)].map((m) => m[1]);
  const uniq = [...new Set(linked)];
  ok('the portal names eight layers', uniq.length === 8, uniq.join(' '));
  for (const slug of uniq) {
    ok(`  ${slug} exists`, existsSync(join(REPO, 'src', 'content', 'strata', `${slug}.md`)));
  }
}

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