#!/usr/bin/env node
/**
 * verify-the-order-is-the-claim.mjs: the check for /strata/the-order-is-the-claim/.
 *
 *   node verify-the-order-is-the-claim.mjs
 *
 * The page's subject is checks that assert a value and never an arrangement, so
 * a check for it that asserted only values would be the joke telling itself.
 * Seven families, and the order is deliberate: each sees something the one
 * before it cannot.
 *
 *   1. the arithmetic, against a second implementation of d(n) and against the
 *      published highly-composite sequence
 *   2. THE PAGE'S CENTRAL PROPERTY, made falsifiable: every arrangement defect
 *      must leave the multiset of displayed pairs exactly as the engine made it.
 *      If that ever fails, the page's whole thesis is false and this check says so
 *   3. the truth table, pinned as literals AND re-derived from what each check
 *      means, because a table asserted against itself asserts nothing
 *   4. which defects lie, decided mechanically from the page's stated claim
 *      rather than from the label in the source
 *   5. the shipped defaults, so the page cannot go out with a defect switched on
 *   6. the rendered DOM in a real browser: the rows a reader sees, in the order
 *      a reader sees them, and the five lights answering the way family 3 says
 *   7. the corpus figures in the page's data block, re-derived from the
 *      committed run records, plus the instrument's own control re-run from here
 *
 * Family 6 asserts ORDER, not just contents, which is the twenty lines this
 * whole layer exists to argue for. It is meant to be copied.
 */

import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import { spawnSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
import { loadChromium } from './research/verifier-independence/lib/playwright-resolve.mjs';
import { readRecords, readAudit, digitSweepPopulation } from './research/verifier-independence/lib/order-records.mjs';

const ROOT = path.dirname(new URL(import.meta.url).pathname);
const SLUG = 'the-order-is-the-claim';
const DIR = path.join(ROOT, 'public', 'strata', SLUG);
const PAGE = path.join(DIR, 'index.html');
const RESEARCH = path.join(ROOT, 'research', 'verifier-independence');

let pass = 0, fail = 0;
const log = [];
function ok(cond, what, detail) {
  if (cond) { pass++; log.push(`  ok    ${what}`); return true; }
  fail++; log.push(`  FAIL  ${what}${detail ? `\n          ${detail}` : ''}`);
  return false;
}

const E = await import(pathToFileURL(path.join(DIR, 'engine.js')).href);
const html = fs.readFileSync(PAGE, 'utf8');

/* ── 1. the arithmetic ────────────────────────────────────────────────────── */

log.push('[1] d(n), two ways, and against the published sequence:');
{
  let agree = true, worst = null;
  for (let n = 1; n <= 4000; n++) {
    if (E.divisorCount(n) !== E.divisorCountByFactorisation(n)) { agree = false; worst = n; break; }
  }
  ok(agree, 'trial division and prime factorisation agree on d(n) for every n up to 4,000',
    worst ? `first disagreement at n = ${worst}` : '');
  ok(E.divisorCount(60) === 12, 'd(60) = 12, which the page asserts on its face');
  ok(E.divisorCount(1) === 1 && E.divisorCount(2) === 2 && E.divisorCount(36) === 9,
    'd(1) = 1, d(2) = 2, d(36) = 9');

  /* A002182, the highly composite numbers: each sets a record for d. Reading
     the record-setters out of the ranking is an independent route to the same
     arithmetic, and the sequence is published, so this leaves the repository. */
  const A002182 = [1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520];
  const records = [];
  let best = 0;
  for (let n = 1; n <= 2520; n++) { const d = E.divisorCount(n); if (d > best) { best = d; records.push(n); } }
  ok(JSON.stringify(records) === JSON.stringify(A002182),
    'the record-setters up to 2,520 are exactly the published highly composite numbers (A002182)',
    `got ${records.join(',')}`);
}

/* ── 2. the central property, falsifiable ─────────────────────────────────── */

log.push('\n[2] every arrangement defect keeps every number the engine computed:');
{
  const key = rs => rs.map(r => `${r.n}:${r.d}`).sort().join(',');
  const N = 300;
  const trueRows = E.rank(N);
  for (const d of Object.keys(E.DEFECTS)) {
    const { engineRows, shown } = E.bench(N, d);
    ok(key(shown) === key(engineRows),
      `${d}: what is shown is a permutation of what the engine returned`);
    if (d === 'properDivisors') continue;
    ok(key(shown) === key(trueRows),
      `${d}: and of the TRUE ranking, so not one displayed number differs from the correct one`);
  }
  /* the one defect that is allowed to change a value, so the family above cannot
     pass by the mutation simply never doing anything */
  const pd = E.bench(300, 'properDivisors');
  ok(key(pd.shown) !== key(trueRows),
    'the one value-changing defect DOES change the multiset, so the test above could have failed');
}

/* ── 3. the truth table, pinned and re-derived ────────────────────────────── */

log.push('\n[3] the truth table, as a literal and as a meaning:');
const TRUTH_N = 200;
/* Pinned. A change to any check or defect must be a deliberate edit here. */
const EXPECTED = {
  none: { permutation: 0, spot: 0, sorted: 0, reference: 0, screen: 0 },
  comparatorReversed: { permutation: 0, spot: 0, sorted: 1, reference: 1, screen: 0 },
  tieBreakFlipped: { permutation: 0, spot: 0, sorted: 0, reference: 1, screen: 0 },
  properDivisors: { permutation: 0, spot: 1, sorted: 0, reference: 1, screen: 0 },
  renderReversed: { permutation: 0, spot: 0, sorted: 1, reference: 1, screen: 1 },
  renderRotated: { permutation: 0, spot: 0, sorted: 1, reference: 1, screen: 1 },
  renderSwapPair: { permutation: 0, spot: 0, sorted: 1, reference: 1, screen: 1 },
  renderShuffleTies: { permutation: 0, spot: 0, sorted: 0, reference: 1, screen: 1 },
};
const table = {};
{
  for (const d of Object.keys(E.DEFECTS)) {
    const { results, shown, engineRows } = E.bench(TRUTH_N, d);
    table[d] = Object.fromEntries(E.CHECKS.map(c => [c.id, results[c.id] ? 1 : 0]));
    ok(JSON.stringify(table[d]) === JSON.stringify(EXPECTED[d]),
      `${d}: the five lights are what this file pins`,
      `pinned ${JSON.stringify(EXPECTED[d])}\n          got    ${JSON.stringify(table[d])}`);

    /* and the same cells derived from what each check MEANS, so the pin is not
       simply a photograph of whatever the code happens to do today */
    const rises = shown.some((r, i) => i > 0 && r.d > shown[i - 1].d);
    ok((table[d].sorted === 1) === rises,
      `${d}: the order light is red exactly when the displayed divisor column rises`);
    const sameAsEngine = shown.every((r, i) => r.n === engineRows[i].n && r.d === engineRows[i].d);
    ok((table[d].screen === 1) === !sameAsEngine,
      `${d}: the screen light is red exactly when the screen differs from the engine`);
  }
  ok(E.CHECKS.every(c => Object.keys(E.DEFECTS).some(d => table[d][c.id] === 1) || c.id === 'permutation'),
    'every check except the permutation one is red somewhere, so none of them is inert');
  ok(Object.keys(E.DEFECTS).every(d => table[d].permutation === 0),
    'THE HEADLINE: the permutation check is green on every row, including every lie');
}

/* ── 4. which defects lie, decided from the page's claim ──────────────────── */

log.push('\n[4] the lie column, decided mechanically rather than by its label:');
{
  /* The page's stated claim, in the page's own words, is a ranking by divisor
     count, most first, and nothing about ties. A defect lies exactly when the
     displayed table violates that, or shows a wrong divisor count. */
  const trueD = new Map();
  for (let n = 2; n <= TRUTH_N; n++) trueD.set(n, E.divisorCount(n));
  for (const d of Object.keys(E.DEFECTS)) {
    const { shown } = E.bench(TRUTH_N, d);
    const rises = shown.some((r, i) => i > 0 && r.d > shown[i - 1].d);
    const wrongValue = shown.some(r => trueD.get(r.n) !== r.d);
    ok((rises || wrongValue) === E.DEFECTS[d].lies,
      `${d}: labelled lies=${E.DEFECTS[d].lies}, and it ${rises || wrongValue ? 'does' : 'does not'} contradict the stated claim`);
  }
  const liars = Object.keys(E.DEFECTS).filter(d => E.DEFECTS[d].lies);
  const honest = Object.keys(E.DEFECTS).filter(d => !E.DEFECTS[d].lies && d !== 'none');
  ok(liars.length === 5 && honest.length === 2,
    `five defects lie and two rearrange harmlessly`, `${liars.length} and ${honest.length}`);
  ok(liars.every(d => table[d].sorted === 1 || table[d].spot === 1),
    'THE PAIR: the order check and the spot value check together are red on every lie');
  ok(honest.every(d => table[d].sorted === 0 && table[d].spot === 0),
    'and green on both harmless rearrangements, which no other pair here manages');
  ok(honest.every(d => table[d].reference === 1),
    'while the row-for-row reference check goes red on both, asserting more than the page claims');
  const alone = E.CHECKS.filter(c => liars.every(d => table[d][c.id] === 1) && honest.every(d => table[d][c.id] === 0));
  ok(alone.length === 0, 'and no single check here is red on exactly the lies and nothing else',
    `these were: ${alone.map(c => c.id).join(',')}`);
}

/* ── 5. the shipped defaults ──────────────────────────────────────────────── */

log.push('\n[5] the page ships with nothing broken:');
{
  ok(/\bdefect\s*=\s*'none'\s*;/.test(html), 'the page opens with no defect selected');
  ok(/\bN\s*=\s*200\s*,/.test(html), 'and with the ranking it says it opens with');
  ok(html.includes('id="ntext">200<'), 'and the sentence naming that size agrees');
  const src = fs.readFileSync(path.join(DIR, 'engine.js'), 'utf8');
  ok(!/Math\.random|Date\.now/.test(src), 'nothing in the engine is random or clock-dependent');
}

/* ── 6. a real browser, asserting the ORDER a reader sees ─────────────────── */

log.push('\n[6] the rendered page, in a browser, row by row and light by light:');
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript',
  '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
  '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.txt': 'text/plain' };
const PUBLIC = path.join(ROOT, 'public');
const server = http.createServer((req, res) => {
  let p;
  try { p = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); }
  catch { res.writeHead(400); res.end(); return; }
  if (p.endsWith('/')) p += 'index.html';
  const f = path.join(PUBLIC, p);
  if (!f.startsWith(PUBLIC + path.sep) || !fs.existsSync(f) || !fs.statSync(f).isFile()) { res.writeHead(404); res.end('no'); return; }
  res.writeHead(200, { 'content-type': MIME[path.extname(f)] || 'application/octet-stream' });
  res.end(fs.readFileSync(f));
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
const BASE = `http://127.0.0.1:${server.address().port}`;
const chromium = await loadChromium();
const browser = await chromium.launch({ args: ['--no-sandbox'] });
const page = await browser.newPage();
const pageErrors = [];
page.on('pageerror', e => pageErrors.push(String(e.message).slice(0, 160)));
await page.goto(`${BASE}/strata/${SLUG}/`, { waitUntil: 'load', timeout: 30000 });
await page.waitForTimeout(700);

const readRig = () => page.evaluate(() => ({
  rows: [...document.querySelectorAll('#tbody tr')].map(tr => [...tr.children].map(td => td.textContent)),
  lights: [...document.querySelectorAll('#lights li')].map(li => li.querySelector('.dot').classList.contains('r') ? 1 : 0),
  verdict: document.getElementById('verdict').textContent,
  pressed: [...document.querySelectorAll('#ectl button, #dctl button')]
    .filter(b => b.getAttribute('aria-pressed') === 'true').map(b => b.dataset.id),
}));

{
  ok(pageErrors.length === 0, 'the page loads without throwing', pageErrors.join('; '));
  const shipped = await readRig();
  ok(shipped.pressed.join(',') === 'none', 'it arrives with no defect pressed', shipped.pressed.join(','));

  for (const d of Object.keys(E.DEFECTS)) {
    if (d !== 'none') await page.click(`[data-id="${d}"]`);
    else await page.click('#ectl button[data-id="none"]');
    await page.waitForTimeout(120);
    const seen = await readRig();

    /* the first fourteen rows, in the order a reader sees them */
    const want = E.display(E.rank(200, E.engineOptionsFor(d)), d).slice(0, 14);
    const got = seen.rows.map(r => ({ rank: r[0], n: Number(r[1]), d: Number(r[2]) }));
    ok(got.length === 14 && want.every((w, i) => got[i].n === w.n && got[i].d === w.d),
      `${d}: the fourteen rows on screen are the right rows IN THE RIGHT ORDER`,
      `screen ${got.slice(0, 5).map(r => r.n + '/' + r.d).join(' ')}\n          engine ${want.slice(0, 5).map(r => r.n + '/' + r.d).join(' ')}`);
    ok(got.every((r, i) => r.rank === String(i + 1)),
      `${d}: the rank column counts from one down the page as rendered`);

    const wantLights = E.CHECKS.map(c => EXPECTED[d][c.id]);
    ok(seen.lights.join('') === wantLights.join(''),
      `${d}: the five lights on screen are ${wantLights.join('')}`,
      `screen ${seen.lights.join('')}`);
    ok(E.DEFECTS[d].lies ? /lying/.test(seen.verdict) : !/lying/.test(seen.verdict),
      `${d}: the page says out loud whether it is lying`);
  }
}

/* ── 7. the corpus block, and the instrument's own control ────────────────── */

log.push('\n[7] the corpus figures, re-derived from the committed records:');
{
  const m = html.match(/<script type="text\/plain" id="results-data">([\s\S]*?)<\/script>/);
  let data = null;
  try { data = JSON.parse(m[1]); } catch { data = null; }
  if (!ok(data && data.sweep, 'the page carries a filled results block')) {
    log.push('          run: node research/verifier-independence/fill-order-page.mjs');
  } else {
    const { files: shardFiles, shards, records } = readRecords(RESEARCH);
    ok(shardFiles.length > 0, 'the run records are committed');
    ok(shards.every(s => s.complete), 'every shard finished');
    const by = v => records.filter(r => r.verdict === v).length;
    const s = data.sweep;
    ok(s.total === records.length, `the population on the page is the ${records.length} records`, `page says ${s.total}`);
    for (const v of ['sees', 'blind', 'indeterminate', 'artifact', 'unmeasured']) {
      ok(s[v] === by(v), `${v}: page ${s[v]}, records ${by(v)}`);
    }
    ok(s.decided === by('sees') + by('blind'), 'the decided count is sees plus blind');
    /* the restricted split, and the audit pass it rests on. This is the number
       the page leads with, so it is the one this check leans on hardest. */
    const { files: auditFiles, byKey: auditBy } = readAudit(RESEARCH);
    ok(auditFiles.length > 0, 'the audit-only pass is committed too');
    const key = r => `${r.area}/${r.slug}|${r.rel}`;
    ok(records.every(r => auditBy.has(key(r))),
      'every record in the sweep has an audit row, so nothing is restricted on missing data');
    ok([...auditBy.values()].every(a => a.probeMode === 'observe'),
      'THE AUDIT LOOKED AT THE TRUE PAGE: every audit row was taken in observe mode, which moves nothing');
    const movedOrdered = r => (auditBy.get(key(r))?.movedAudit?.ordered ?? 0);
    const hasOrdered = r => movedOrdered(r) > 0;
    const seesO = records.filter(r => r.verdict === 'sees' && hasOrdered(r)).length;
    const blindO = records.filter(r => r.verdict === 'blind' && hasOrdered(r)).length;
    ok(s.ordered.sees === seesO && s.ordered.blind === blindO,
      `the restricted split is the records' own: ${seesO} see, ${blindO} blind`);
    ok(s.ordered.decided === seesO + blindO, 'and its total is those two');
    ok(s.ordered.reachedContainers === records.reduce((a, r) => a + (auditBy.get(key(r))?.movedAudit?.containers || 0), 0)
      && s.ordered.reachedOrdered === records.reduce((a, r) => a + movedOrdered(r), 0),
      `the reached-container counts are the audit's own: ${s.ordered.reachedOrdered} of ${s.ordered.reachedContainers}`);
    ok(s.ordered.reachedOrdered <= s.ordered.reachedContainers
      && s.ordered.decided <= s.decided,
      'the restricted population is a subset of the decided one, which is a subset of the whole');
    const looseDecided = records.filter(r => (r.verdict === 'sees' || r.verdict === 'blind') && (r.audit?.ordered ?? 0) > 0).length;
    ok(s.ordered.looseDecided === looseDecided,
      `the loose reading is reported beside the tight one: ${looseDecided}`);

    /* The audit's own error budget, both directions, added after an adversarial
       read of this page found the tight audit implemented WITHOUT the one-tag
       clause its own description states, and counting rows of buttons the page
       had promised to exclude. Both are enforced now, and both counts are
       published rather than quietly dropped. */
    const aud = k => records.reduce((a, r) => a + (auditBy.get(key(r))?.movedAudit?.[k] || 0), 0);
    for (const k of ['orderedByText', 'orderedThreeOnly', 'rejectedMixedTag', 'rejectedControl']) {
      const src = k.startsWith('ordered') ? k.replace('ordered', '').replace(/^./, c => c.toLowerCase()) : k;
      ok(s[k] === aud(src), `${k}: page ${s[k]}, audit ${aud(src)}`);
    }
    ok(s.rejectedMixedTag > 0 || s.rejectedControl > 0,
      'the two exclusions actually excluded something, so enforcing them was not cosmetic');
    ok(s.orderedThreeOnly <= s.ordered.reachedOrdered && s.orderedByText <= s.ordered.reachedOrdered,
      'the chance-prone subsets are subsets of the ordered count');

    /* The pre-rescue figures, because the solitary re-runs moved the headline. */
    const parallel = shards.filter((_, i) => Number(shardFiles[i].match(/\d+/)[0]) < 3).flatMap(sh => sh.records);
    const preBy = v => parallel.filter(r => r.verdict === v).length;
    ok(s.pre.blind === preBy('blind') && s.pre.sees === preBy('sees')
      && s.pre.artifact === preBy('artifact') && s.pre.unmeasured === preBy('unmeasured'),
      `the pre-rescue figures are the parallel shards' own: ${preBy('blind')} blind, ${preBy('sees')} sees, ${preBy('artifact')} artifact`);
    ok(s.pre.blind / s.pre.decided < s.blind / s.decided,
      'and the page says out loud that the re-runs raised the headline rather than lowering it');

    /* Every figure the page prints inside a SENTENCE, not only in its block. */
    const inSentence = [...html.matchAll(/<span class="mono" data-fig="([a-zA-Z]+)">([^<]*)<\/span>/g)];
    ok(inSentence.length > 0, 'the page carries in-sentence figures marked data-fig');
    for (const [, name, printed] of inSentence) {
      ok(name in (data.figures || {}), `data-fig="${name}" is a figure the filler knows how to write`);
      ok(String(data.figures?.[name]?.toLocaleString('en-US')) === printed,
        `the sentence figure ${name} prints ${printed}, and the record says ${data.figures?.[name]}`);
    }
    const fig = data.figures || {};
    ok(fig.population === records.length && fig.blind === by('blind') && fig.sees === by('sees')
      && fig.decided === by('sees') + by('blind') && fig.orderedBlind === blindO && fig.orderedSees === seesO,
      'and every one of those figures is the records\' own, not a second copy');
    ok(s.moved === records.reduce((a, r) => a + (r.witness?.moved || 0), 0),
      'the count of moved insertions is the records\' own');

    /* the population is the previous experiment's answer, and that is checkable */
    const screenSees = digitSweepPopulation(RESEARCH);
    const mine = records.map(r => `${r.area}/${r.slug}|${r.rel}`);
    ok(mine.length === screenSees.length && mine.every(k => screenSees.includes(k)),
      `the population is exactly the ${screenSees.length} pairs the digit sweep found red, and nothing else`,
      `order run has ${mine.length}`);

    ok(records.every(r => r.verdict !== 'sees' || (r.brokeErrors || []).length === 0),
      'no check counted as seeing the arrangement did so on a page that threw');
    ok(records.filter(r => r.verdict === 'blind').every(r => (r.witness?.moved || 0) > 0),
      'every blind verdict was recorded on a page where the probe demonstrably moved something');
  }

  /* the two fixes the page says were made, and the proof it says exists */
  const FIXED = [
    ['order-fix1.json', 'the-encoding-your-text-file-admits-to'],
    ['order-fix2.json', 'hostage-sublime'],
  ];
  const sweepRecords = readRecords(RESEARCH).records;
  for (const [record, slug] of FIXED) {
    const p = path.join(RESEARCH, record);
    if (!ok(fs.existsSync(p), `${slug}: the re-run under the permutation is committed (${record})`)) continue;
    const j = JSON.parse(fs.readFileSync(p, 'utf8'));
    const rs = j.records.filter(r => r.slug === slug);
    ok(rs.length > 0 && rs.every(r => r.verdict === 'sees'),
      `${slug}: on its own, under the permutation, it now goes red and stays green under the placebo`,
      rs.map(r => r.verdict).join(','));
    ok(rs.every(r => (r.brokeErrors || []).length === 0),
      `${slug}: and its page threw nothing, so the red is the arrangement and not breakage`);
    ok(html.includes(`/strata/${slug}/`), `${slug}: the page links to the layer it says it fixed`);
    /* the sweep's own verdict is left as measured, which is the claim the page makes */
    const inSweep = sweepRecords.find(r => r.slug === slug);
    ok(inSweep && inSweep.verdict === 'blind',
      `${slug}: and the sweep still records it blind, as the photograph taken before the repair`);
  }

  /* the control the page cites, re-run from here rather than quoted */
  const ctl = spawnSync(process.execPath, [path.join(RESEARCH, 'order-control.mjs')],
    { cwd: ROOT, encoding: 'utf8', timeout: 180000 });
  ok(ctl.status === 0, 'the instrument\'s own control still passes, run from this check',
    (ctl.stdout || '').split('\n').filter(l => /FAIL/.test(l)).slice(0, 3).join('\n          '));
  ok(/VALUES STAYS GREEN under the permutation/.test(ctl.stdout || ''),
    'and it is the control the page describes: a value check that stays green');
}

/* ── report ───────────────────────────────────────────────────────────────── */

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

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