// verify-what-lincoln-said.mjs — the moat for /strata/what-lincoln-said/.
//
//   node verify-what-lincoln-said.mjs            (from the repository root)
//   node verify-what-lincoln-said.mjs --mutate   also run the controls that must fail
//
// What this checks, in order: that the engine is an engine; that the readings
// come from the bytes they claim; that the arithmetic is a metric; that the two
// EXTERNAL answer keys still agree with it; that the field probes can say no;
// and that the shipped page is what the apparatus builds and prints only
// numbers the apparatus produced.
//
// The controls are the part worth reading. A verifier nobody has watched fail
// is a verifier nobody should believe, so --mutate corrupts the inputs on
// purpose and asserts that the checks go red. If a mutation leaves everything
// green, the check it was aimed at is decorative and should be deleted.
import { readFileSync, existsSync, readdirSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = dirname(fileURLToPath(import.meta.url));
const R = join(ROOT, 'research', 'what-lincoln-said');
const PAGE = join(ROOT, 'public', 'strata', 'what-lincoln-said', 'index.html');
const MUTATE = process.argv.includes('--mutate');

const { tokenise, wordEditDistance, pairwiseAlign, multipleAlign, orthographicKey } = await import(join(R, 'align.mjs'));
const { runField } = await import(join(R, 'field.mjs'));

let pass = 0, fail = 0;
const ok = (c, m, extra) => { if (c) { pass++; } else { fail++; console.log('  FAIL ' + m + (extra ? '  ' + extra : '')); } };
const section = t => console.log(`\n${t}`);

const data = JSON.parse(readFileSync(join(R, 'data.json'), 'utf8'));
const readings = data.objects.flatMap(o => o.readings.map(r => ({ ...r, object: o.id, kind: o.kind })));
const byId = new Map(readings.map(r => [r.id, r]));
const keys = id => tokenise(byId.get(id).text).words.map(t => t.key);

// ── 1 · the engine ──────────────────────────────────────────────────────────
section('1 · the engine checks itself');
{
  const r = spawnSync('node', [join(R, 'align.mjs'), '--selftest'], { encoding: 'utf8' });
  const n = (r.stdout.match(/(\d+) passed, (\d+) failed/) || []);
  ok(r.status === 0, 'align.mjs --selftest exits 0', r.stdout.split('\n').filter(l => /FAIL/.test(l)).join(' '));
  ok(Number(n[1]) >= 20 && Number(n[2]) === 0, `the engine's own suite is green (${n[1] || '?'} checks)`);
}

// ── 2 · the readings come from the bytes they claim ─────────────────────────
section('2 · every reading is pinned to an archived page');
for (const r of readings) {
  const f = join(R, 'sources', 'raw', r.file);
  ok(existsSync(f), `${r.id}: the archived source ${r.file} is committed`);
  if (!existsSync(f)) continue;
  const got = createHash('sha256').update(readFileSync(f)).digest('hex');
  ok(got === r.sha256, `${r.id}: ${r.file} still hashes to the value data.json records`);
  ok(/^["“]?Four ?score/i.test(r.text), `${r.id}: opens on "Four score"`);
  ok(/perish from the earth[.”"]?$/i.test(r.text.trim()), `${r.id}: closes on "perish from the earth"`);
  ok(r.tokens.length > 200 && r.tokens.length < 320, `${r.id}: ${r.tokens.length} words, a plausible length`);
}
// A range, not a fixed count: readings are added as sources are found, and the
// figure moved from 19 to 21 when the wall was read directly. What must hold is
// that the corpus is real and that every object has more than one reading
// wherever more than one exists.
ok(readings.length >= 19, `${readings.length} readings gathered`);
ok(data.objects.filter(o => o.readings.length > 1).length >= 6, 'at least six objects carry more than one reading');
ok(data.objects.length === 7, `7 objects`, `found ${data.objects.length}`);
for (const o of data.objects) ok(o.readings.filter(r => r.primary).length === 1, `${o.id}: exactly one primary reading`);

// ── 3 · the arithmetic is a metric ──────────────────────────────────────────
section('3 · the distances behave like distances');
{
  const ids = readings.map(r => r.id);
  let sym = true, diag = true, tri = true, agree = true;
  for (const a of ids) {
    if (data.distance[a][a] !== 0) diag = false;
    for (const b of ids) {
      if (data.distance[a][b] !== data.distance[b][a]) sym = false;
      if (wordEditDistance(keys(a), keys(b)) !== data.distance[a][b]) agree = false;
    }
  }
  for (let i = 0; i < ids.length; i += 3) for (let j = 0; j < ids.length; j += 5) for (let k = 0; k < ids.length; k += 7) {
    if (data.distance[ids[i]][ids[k]] > data.distance[ids[i]][ids[j]] + data.distance[ids[j]][ids[k]]) tri = false;
  }
  ok(diag, 'a reading is zero from itself');
  ok(sym, 'the matrix is symmetric');
  ok(tri, 'the triangle inequality holds across the sampled triples');
  ok(agree, 'every stored distance is what align.mjs recomputes right now');
  const nonZero = ids.filter(a => ids.some(b => data.distance[a][b] > 0)).length;
  ok(nonZero === ids.length, 'control: no reading is at distance zero from everything (the matrix is not empty)');
}

// ── 4 · external answer key: the Library of Congress's own collation ────────
section('4 · external control, the Library of Congress collation');
{
  const r = spawnSync('node', [join(R, 'loc-control.mjs')], { encoding: 'utf8' });
  ok(r.status === 0, 'loc-control.mjs exits 0');
  const hay = (r.stdout.match(/engine flags (\d+) distinct word-forms in Hay;\s+(\d+) of them/) || []);
  ok(hay[1] && hay[1] === hay[2], `every word-form the engine flags in Hay is one the Library marked (${hay[2] || '?'} of ${hay[1] || '?'})`);
  ok(/control: a text aligned against itself flags nothing/.test(r.stdout) && !/FAIL/.test(r.stdout), 'its own self-alignment control passes');
}

// ── 5 · external answer key: Barton, 1930 ───────────────────────────────────
section('5 · external control, a hand count from 1930');
{
  const b = data.barton;
  const quoted = readFileSync(join(R, 'sources', 'raw', b.file), 'utf8').replace(/\s+/g, ' ');
  // Barton's sentence must actually be in the scanned book, not just in our note.
  ok(quoted.includes('first draft, 239; second'), 'Barton\'s table is present verbatim in the scanned 1930 text');
  ok(b.claims.length === 3, 'three of Barton\'s numbers are claimed, not all six');
  for (const c of b.check) {
    ok(c.perReading.length >= 2, `${c.manuscript}: Barton's number is tested against every reading, not just one`);
    ok(c.anyAgrees, `${c.manuscript}: some reading reproduces Barton's ${c.expect}`,
      `got ${c.perReading.map(r => r.got).join(', ')}`);
  }
  ok(data.barton.otherCompounds.length === 0,
    'Barton\'s rule names the only hyphenated compounds in the corpus, so it cannot have been widened to fit');
  // Barton must be a real discriminator: if every reading hit every number, the
  // control would be vacuous.
  const someMiss = b.check.some(c => c.perReading.some(r => !r.agrees));
  ok(someMiss, 'control: Barton\'s counts are not satisfied by every reading, so agreeing with him means something');
}

// ── 6 · the wall ────────────────────────────────────────────────────────────
section('6 · the carved wall against the copy it reproduces');
{
  const m = data.memorialVsBliss;
  ok(m.distance >= m.changes, 'the edit count is at least the change count');
  ok(m.substantive === 0, 'the wall changes no word of the Bliss copy',
     `${m.substantive} substantive difference(s): ${[...m.items.lexical.map(x => `${x.a}/${x.b}`), ...m.items.onlyA.map(x => x.word)].join(', ')}`);
  ok(m.changes === 1, `the wall differs from the manuscript at exactly one place (${m.changes})`);
  ok(m.items.orthographic.length === 1 && /battle-?field/i.test(m.items.orthographic[0].a),
     'and the one place is the hyphen in "battle-field"');
  ok(m.distance > 0, 'control: the wall is not byte-identical to the manuscript either');
  // The classifier must still be able to tell the three kinds apart.
  ok(orthographicKey('Four') + orthographicKey('score') === orthographicKey('Fourscore'),
     'control: the division test identifies "Four score" with "Fourscore"');
  ok(orthographicKey('upon') !== orthographicKey('on'), 'control: and does NOT identify "upon" with "on"');
  ok(orthographicKey('battle-field') === orthographicKey('battlefield'),
     'control: a hyphen dropped inside one word is the same word');
}

// ── 6a · the stone, read off a photograph ───────────────────────────────────
section('6a · the wall read directly, and the transcriptions of it');
{
  const st = data.stone;
  ok(st.lines.length === 46, `46 lines as cut (${st.lines.length})`);
  ok(st.commas === 0, `no comma anywhere in the inscription (${st.commas} found)`);
  ok(st.wordBreaks.length === 4, `four words divided across a line (${st.wordBreaks.length})`);
  ok(st.rejoined.length === 4, 'each division is recorded with the word it rejoins into');
  // Every rejoin must be a word the manuscript has. This is what keeps the
  // reading of a photograph honest: it is checked against a text nobody carved.
  const bliss = byId.get(data.objects.find(o => o.id === 'bliss').readings.find(r => r.primary).id).text.toUpperCase();
  for (const r of st.rejoined) ok(bliss.includes(r.word), `the rejoined "${r.word}" is a word the Bliss manuscript contains`);
  ok(!bliss.includes('HALLOWTHIS'), 'control: a wrong rejoin would NOT be a word of the manuscript');
  ok(st.photograph.sha256 && st.photograph.sha256.length === 64, 'the photograph is pinned by SHA-256');
  ok(Array.isArray(st.photograph.cropBox) && st.photograph.cropBox.length === 4, 'and the crop box is recorded, so the reading is reproducible');
  ok(/GFDL/.test(st.photograph.licence), 'the photograph\'s licence is recorded (it is why the image is not shipped)');
  ok(!existsSync(join(ROOT, 'public', 'strata', 'what-lincoln-said', 'panel.jpg')),
     'and the GFDL image is NOT redistributed on the site');

  // The independent cross-check has to exist and has to agree.
  ok(st.crosscheck && st.crosscheck.agrees,
     'an independent transcription of the same photograph agrees word for word');
  ok(st.crosscheck && /Wikisource/i.test(st.crosscheck.authority), 'and it is named');

  // The finding: the readings of the wall split into those that agree with the
  // stone and one that does not.
  const w = data.withinObject.find(x => x.object === 'memorial');
  ok(w.readings.length === 4, `four readings of the wall (${w.readings.length})`);
  const agree = w.pairs.filter(p => p.distance === 0).length;
  const differ = w.pairs.filter(p => p.distance > 0);
  ok(agree === 3, `three pairs are identical word for word (${agree})`);
  ok(differ.length === 3 && differ.every(p => p.a.endsWith('@loc') || p.b.endsWith('@loc')),
     'and every pair that differs involves the Library of Congress transcription');
  ok(differ.every(p => p.substantive === 0), 'none of those differences is a different word');
  ok(differ.every(p => p.divisions.length === 5), 'each is the same five word divisions');
  ok(w.pairsWithSubstantiveDisagreement === 0, 'control: no reading of the wall disputes a word with another');
}

// ── 6b · the standard edition ───────────────────────────────────────────────
section('6b · external control, Basler 1953');
{
  const b = data.basler;
  ok(b.footnotes.length >= 4, `${b.footnotes.length} footnotes quoted from the standard edition`);
  for (const f of b.footnotes) ok(f.present, `footnote ${f.n} is present verbatim in the archived scan (a quotation that cannot drift)`);
  const scan = readFileSync(join(R, 'sources', 'raw', b.file), 'utf8');
  ok(createHash('sha256').update(readFileSync(join(R, 'sources', 'raw', b.file))).digest('hex') === b.sha256, 'the scan still hashes to the recorded value');
  ok(scan.includes('ROY  P.  BASLER'), 'control: the file really is the Collected Works and not some other book');
  ok(scan.includes('VII'), 'control: and it is volume VII');
  // The primary reading of the Bliss copy must now agree with Basler on both
  // variants he names for it. This is the check that would have caught the
  // original mistake, so it is the one that matters most in this section.
  const blissPrimary = data.objects.find(o => o.id === 'bliss').readings.find(r => r.primary).id;
  const blissResults = b.results.filter(r => r.object === 'bliss' && r.reading === blissPrimary);
  ok(blissResults.length === 2, 'both Bliss variants are tested against the primary reading', `found ${blissResults.length}`);
  ok(blissResults.every(r => r.agrees), 'the primary Bliss reading agrees with Basler on every variant he names',
    blissResults.filter(r => !r.agrees).map(r => r.variant).join(', '));
  // And the control: some reading must FAIL, or the test proves nothing.
  ok(b.failing.length > 0, 'control: at least one reading disagrees with him, so agreeing is informative');
  ok(b.results.length > b.failing.length, 'control: and at least one agrees, so the test is not always-false');
}

// ── 6c · independence ───────────────────────────────────────────────────────
section('6c · nineteen readings is not nineteen witnesses');
{
  const i = data.independence;
  ok(i.readings === readings.length, 'the independence count covers every reading');
  ok(i.distinct < i.readings, `${i.readings} readings, only ${i.distinct} distinct word for word`);
  ok(i.distinct > 8, 'control: they have not collapsed to a handful');
  for (const p of i.identicalPairs) {
    ok(wordEditDistance(keys(p.a), keys(p.b)) === 0, `${p.a} and ${p.b} really are at distance zero`);
  }
}

// ── 6d · a quotation on the page, asserted against its source ───────────────
section('6d · the Everett letter quoted on the page is in the archived page');
{
  const f = join(R, 'sources', 'raw', 'loc-everett-letter.html');
  ok(existsSync(f), 'the Library of Congress transcription of the letter is committed');
  const src = readFileSync(f, 'utf8').replace(/<[^>]+>/g, ' ').replace(/&amp;/g, '&').replace(/\s+/g, ' ');
  const html = readFileSync(PAGE, 'utf8');
  const quoted = 'I should be glad, if I could flatter myself that I came as near to the central idea of the occasion, in two hours, as you did in two minutes.';
  ok(src.includes(quoted), 'the sentence is present verbatim in the archived transcription');
  ok(html.replace(/\s+/g, ' ').includes(quoted), 'and the shipped page quotes it verbatim, character for character');
  ok(!src.includes('as you did in three minutes'), 'control: the archived page does not contain a nearby variant, so the match is not loose');
}

// ── 7 · the field witnesses ─────────────────────────────────────────────────
section('7 · the field probes can say no');
{
  const f = runField();
  ok(f.total === 8, `8 newspaper pages fetched`, `found ${f.total}`);
  ok(f.usable >= 3 && f.usable < f.total, `${f.usable} of ${f.total} pass both controls, so the controls exclude something`);
  for (const pr of f.probes.filter(p => p.role === 'negative control')) {
    const s = f.summary[pr.id];
    ok(s.foundAllPages === 0 && s.foundTightAllPages === 0,
      `negative control "${pr.phrase}" is found on 0 pages under BOTH matchers`, `strict ${s.foundAllPages}, tight ${s.foundTightAllPages}`);
  }
  for (const pr of f.probes.filter(p => p.role === 'positive control')) {
    const s = f.summary[pr.id];
    ok(s.found === s.of, `positive control "${pr.phrase}" is found on every usable page`);
  }
  const ug = f.summary['under-god'];
  ok(ug.found === ug.of, `"under God" is on every one of the ${ug.of} usable pages`);
  ok(ug.foundTightAllPages >= 7, `"under God" is on ${ug.foundTightAllPages} of the ${ug.allPages} pages fetched`);
  // And it must be absent from the two pre-delivery drafts, or the point evaporates.
  const p = data.phrases.find(x => /under God/i.test(x.phrase));
  ok(p.byObject.nicolay.verdict === 'out', 'and absent from every reading of the Nicolay draft');
  ok(p.byObject.hay.verdict === 'out', 'and absent from every reading of the Hay draft');
  ok(p.byObject.bliss.verdict === 'in', 'control: and present in the Bliss copy, so the phrase test finds it when it is there');
}

// ── 8 · the transcription layer ─────────────────────────────────────────────
section('8 · transcriptions of one object disagree, and by how much');
{
  const multi = data.withinObject.filter(w => w.readings.length > 1);
  ok(multi.length >= 5, `${multi.length} objects have more than one reading`);
  ok(multi.some(w => w.pairsWithSubstantiveDisagreement > 0),
     'at least one object has transcriptions that disagree about WORDS, not only punctuation');
  const hereDisputed = data.objects.filter(o => !data.here.byObject[o.id].agree).length;
  // A range rather than a fixed number: the count moved from 4 to 3 when the
  // Bliss primary was corrected, and a verifier that pins the exact figure would
  // have gone red for the right reason at the wrong moment. What must hold is
  // that some objects disagree and some do not.
  ok(hereDisputed >= 2, `${hereDisputed} objects have readings that disagree how often the address says "here"`);
  ok(hereDisputed < data.objects.length, 'control: not every object is disputed, so the test discriminates');
  ok(data.here.byObject.nicolay.agree, 'control: at least one object\'s readings DO agree, so the test is not always-true');
  ok(!data.stemmaAgrees.allAgree, 'the nearest-neighbour shape is not invariant across transcribers');
  ok(data.stemma.filter(s => s.complete).length >= 2, 'at least two transcribers cover all five manuscripts single-handed');
}

// ── 9 · the invariant core ──────────────────────────────────────────────────
section('9 · what survives every draft');
{
  const inv = data.invariant;
  ok(inv.manuscripts.length === 5, 'five manuscripts in the alignment');
  ok(inv.coreLength > 150 && inv.coreLength < inv.erosion[0].words, `the core (${inv.coreLength}) is smaller than the union (${inv.erosion[0].words})`);
  ok(inv.longestRunLength >= 20 && inv.longestRunLength <= inv.coreLength, `the longest unbroken run is ${inv.longestRunLength}`);
  for (let i = 1; i < inv.erosion.length; i++) ok(inv.erosion[i].words <= inv.erosion[i - 1].words, `erosion is monotone at k=${i + 1}`);
  // The run must actually appear, in order, in every manuscript.
  const run = inv.longestRun.map(w => tokenise(w).words.map(t => t.key)).flat();
  let inAll = true;
  for (const id of inv.manuscripts) {
    const k = keys(id);
    let found = false;
    for (let i = 0; i + run.length <= k.length && !found; i++) {
      let hit = true;
      for (let j = 0; j < run.length; j++) if (k[i + j] !== run[j]) { hit = false; break; }
      if (hit) found = true;
    }
    if (!found) inAll = false;
  }
  ok(inAll, 'the longest run really does occur verbatim in all five manuscripts');
}

// ── 10 · the shipped page ───────────────────────────────────────────────────
section('10 · the page is what the apparatus builds');
{
  ok(existsSync(PAGE), 'the page is on disk');
  const html = readFileSync(PAGE, 'utf8');
  const b = spawnSync('node', [join(R, 'build-page.mjs'), '--check'], { encoding: 'utf8' });
  ok(b.status === 0, 'build-page.mjs --check: the shipped bytes are page.html + data.json', b.stderr.trim());
  ok(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'the closing tags are present (omit them and no inline script runs)');
  ok(html.includes('rel="canonical" href="https://artwaste.land/strata/what-lincoln-said/"'), 'canonical link');
  ok(html.includes('application/ld+json'), 'structured data');
  const m = html.match(/<script id="aw-data" type="application\/json">([\s\S]*?)<\/script>/);
  ok(!!m, 'the data bundle is present');
  const bundle = JSON.parse(m[1]);
  ok(bundle.objects.length === data.objects.length, 'the bundle carries every object');
  const bundleReadings = bundle.objects.flatMap(o => o.readings);
  ok(bundleReadings.length === readings.length, 'the bundle carries every reading');
  ok(bundleReadings.every(r => r.tokens && r.keys && r.tokens.length === r.keys.length),
     'every reading ships both its words and its comparison keys, so the browser can recompute');
  ok(!bundle.objects.some(o => o.readings.some(r => r.alignment || r.distances)),
     'control: the bundle ships NO precomputed alignments, so the page must do the work');
  // Every figure the check panel prints must be derivable, not typed.
  for (const num of [data.memorialVsBliss.changes, data.invariant.coreLength, data.invariant.longestRunLength]) {
    ok(m[1].includes(String(num)), `the bundle carries the figure ${num} the page prints`);
  }
}

// ── 11 · controls that must fail ────────────────────────────────────────────
if (MUTATE) {
  section('11 · mutation controls (each of these MUST go red)');
  const red = (c, m) => { if (!c) { pass++; } else { fail++; console.log('  FAIL (control did not fire) ' + m); } };
  const ids = readings.map(r => r.id);

  // Corrupt a text: the distance to its neighbours must move.
  {
    const before = wordEditDistance(keys('bliss@hd'), keys('memorial@loc'));
    const words = keys('bliss@hd').concat(['zzqx']);
    const after = wordEditDistance(words, keys('memorial@loc'));
    red(after !== before + 1, 'adding one word nobody wrote does not cost exactly one edit');
  }
  // Break the hash: the pinning check must notice.
  {
    const r = byId.get('nicolay@loc-ms');
    red(createHash('sha256').update(Buffer.from('not the file')).digest('hex') === r.sha256,
        'an arbitrary buffer hashes to the recorded value');
  }
  // Break the division test: "upon" and "on" must not be identified.
  red(orthographicKey('upon') === orthographicKey('on'), 'the orthographic key identifies two different words');
  // The field probe must not find a phrase that is not there.
  {
    const f = runField();
    red(f.summary['negative-control'].foundTightAllPages > 0, 'the field probe finds a phrase from the Second Inaugural');
  }
  // The alignment must not be able to align a text to itself at nonzero cost.
  {
    const k = keys(ids[0]);
    red(wordEditDistance(k, k) !== 0, 'a text is a nonzero distance from itself');
  }
  // The erosion must not be flat.
  red(data.invariant.erosion[0].words === data.invariant.erosion[4].words, 'raising the attestation bar removes nothing');
  // A truncated reading must be caught by the extractor's own assertion.
  {
    const bad = 'Four score and seven years ago our fathers brought forth';
    red(/perish from the earth[.”"]?$/i.test(bad.trim()), 'a truncated text passes the closing assertion');
  }
  console.log('  (all mutation controls fired)');
}

console.log(`\n${fail ? 'FAIL' : 'OK'} — ${pass}/${pass + fail} checks` +
  (fail ? `, ${fail} FAILED` : MUTATE ? ' — including the controls that must fail' : ' (run with --mutate for the controls that must fail)'));
process.exit(fail ? 1 : 0);
