// verify-staged.mjs: the artifact gate. Its only job is to read the six b-files
// this directory would deposit and say, term by term, what actually binds each
// number in them. Run it: node verify-staged.mjs   (about 8 s)
//
// WHY THIS EXISTS. The 2026-07-27 mutation probe (research/oeis-term-coverage/)
// corrupted one staged term per directory and watched to see whether anything
// went red. Almost nothing did, because the verifiers compared recomputations
// against literals in their own source and never opened the file that would be
// deposited. This directory's verify.mjs was repaired on 2026-07-23 and does
// read its b-files; this gate is the small fast companion that scripts/check-oeis-staged.mjs
// can run across the whole staging area, and it keeps the three kinds of binding
// visibly apart, because they are worth different amounts:
//
//   recomputed      this script counts the term from the graph, here, now, and
//                   compares it to the staged line.
//   published-pair  the staged line equals path minus cyclic, both read from
//                   the recorded OEIS values. Sønsteby computed those; we did
//                   not. The subtraction is checked; the operands are inherited.
//   drift-guarded   the staged line is compared against expected-extension.mjs,
//                   a provenance table naming the finished run that produced it.
//                   This catches truncation and transcription drift. It is not
//                   a second computation and must never be described as one.
//
// The recompute depths are deliberately shallower than verify.mjs's, so this
// stays cheap enough to run in a sweep. verify.mjs is the deep gate.

import fs from 'node:fs';
import { countByLength } from './engine.mjs';
import { DATA, BELLS, derivableLength } from './derive.mjs';
import { EXPECTED_EXTENSION } from './expected-extension.mjs';

// Depths this gate re-counts from the graph. Chosen for an ~8 s total.
const RECOMPUTE_TO = { 4: 24, 5: 10, 6: 8, 7: 6, 8: 5, 9: 4 };

let pass = 0;
const failures = [];
function check(name, cond, detail = '') {
  if (cond) pass++;
  else failures.push(`${name}${detail ? `   ${detail}` : ''}`);
}

function readBFile(n) {
  const path = new URL(`./b-bells${n}.txt`, import.meta.url);
  const terms = new Map();
  for (const line of fs.readFileSync(path, 'utf8').split(/\r?\n/)) {
    if (line === '') continue;
    const m = /^(\d+) (\d+)$/.exec(line);
    if (!m) { failures.push(`n=${n} b-file has a malformed line: ${JSON.stringify(line)}`); continue; }
    terms.set(Number(m[1]), BigInt(m[2]));
  }
  return terms;
}

const coverage = [];

for (const n of BELLS) {
  const staged = readBFile(n);
  const D = DATA[n];
  const pubTo = derivableLength(n);
  const ext = EXPECTED_EXTENSION[n] || new Map();
  const recomputeTo = Math.min(RECOMPUTE_TO[n], pubTo);

  // (i) recomputed: count from the graph and compare to the staged line.
  const { noncappable, noncappableDirect } = countByLength(n, recomputeTo);
  let recomputedOk = true;
  let directOk = true;
  for (let L = 1; L <= recomputeTo; L++) {
    if (staged.get(L) !== noncappable[L]) recomputedOk = false;
    if (L > 1 && noncappableDirect[L] !== noncappable[L]) directOk = false;
  }
  check(`n=${n} staged L=1..${recomputeTo} recomputed from the graph`, recomputedOk);
  check(`n=${n} the direct endpoint tally agrees with path minus cyclic to L=${recomputeTo}`, directOk);

  // (ii) published-pair: the staged line is the difference of the recorded pair.
  let pairOk = true;
  for (let L = 1; L <= pubTo; L++) {
    const want = L === 1 ? 0n : BigInt(D.p[L - 1]) - BigInt(D.c[L - 1]);
    if (staged.get(L) !== want) pairOk = false;
  }
  check(`n=${n} staged L=1..${pubTo} equals ${D.path} minus ${D.cyclic}`, pairOk);

  // (iii) drift-guarded: the extension terms against the provenance table.
  let extOk = true;
  for (const [L, value] of ext) if (staged.get(L) !== value) extOk = false;
  check(`n=${n} staged extension terms match the provenance table`, extOk);

  // (iv) the file is exactly the union of the two, no more and no less.
  const expectedIndices = new Set([...Array(pubTo).keys()].map((i) => i + 1));
  for (const L of ext.keys()) expectedIndices.add(L);
  const stagedIndices = [...staged.keys()].sort((a, b) => a - b);
  check(
    `n=${n} b-file covers exactly L=1..${Math.max(...expectedIndices)} with no gaps or extras`,
    stagedIndices.length === expectedIndices.size && stagedIndices.every((L) => expectedIndices.has(L)),
    `staged ${stagedIndices.length} terms, expected ${expectedIndices.size}`,
  );

  const extRange = [...ext.keys()].sort((a, b) => a - b);
  coverage.push({
    n,
    terms: stagedIndices.length,
    recomputed: `L=1..${recomputeTo}`,
    publishedPair: `L=1..${pubTo}`,
    driftGuarded: extRange.length ? `L=${extRange[0]}..${extRange[extRange.length - 1]}` : 'none',
  });
}

console.log('per-term binding, by index range:\n');
console.log('  bells  terms  recomputed here  from the published pair  drift-guarded');
for (const c of coverage) {
  console.log(
    `  ${String(c.n).padEnd(6)} ${String(c.terms).padEnd(6)} ${c.recomputed.padEnd(16)} ${c.publishedPair.padEnd(23)} ${c.driftGuarded}`,
  );
}
console.log('');
for (const f of failures) console.log(`  FAIL  ${f}`);
console.log(`${pass}/${pass + failures.length} checks pass${failures.length ? ` (${failures.length} FAILED)` : ''}.`);
process.exit(failures.length ? 1 : 0);
