// verify.mjs - the check for the layer about claims that expire.
//
//   node research/the-sentences-that-rot/verify.mjs
//   node research/the-sentences-that-rot/verify.mjs --mutate
//
// The awkward part of checking this layer is that its subject is sentences that stop being
// true, so its own assertions must not be of that kind. Every number below is derived from
// the frozen snapshot, never from the clock and never from the live corpus, so this file
// gives the same answer next year as it does today. That is not a nicety here: a verifier
// for this page that read the current corpus would rot exactly as its subject does.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { compare } from '../_wave-2026-08-24/reconcile.mjs';
import { measure as measureA } from '../../public/strata/the-sentences-that-rot/engine-a.mjs';
import { measure as measureB } from '../../public/strata/the-sentences-that-rot/engine-b.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const MUTATE = process.argv.includes('--mutate');

const snapshot = JSON.parse(readFileSync(join(HERE, 'data', 'corpus-claims.json'), 'utf8'));
const shipped = JSON.parse(readFileSync(join(ROOT, 'public/strata/the-sentences-that-rot/corpus-claims.json'), 'utf8'));
const html = readFileSync(join(ROOT, 'public/strata/the-sentences-that-rot/index.html'), 'utf8');

let pass = 0, fail = 0;
const chk = (name, cond) => { cond ? (pass++, console.log('  ok   ' + name)) : (fail++, console.log('  FAIL ' + name)); };
// JSON.stringify comparison is KEY-ORDER sensitive, so using it for "do the engines agree"
// tests the order two authors happened to write their object literals in, not their values.
// The reconciler walks both to sorted leaves, which is the thing actually meant.
const eq = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const agree = (a, b) => { const r = compare(a, b, 0); return r.differ.length === 0 && r.onlyA.length === 0 && r.onlyB.length === 0; };

if (!MUTATE) {
  console.log('The snapshot, and the copy the browser fetches');
  chk('the shipped snapshot is byte-identical to the research one', eq(shipped, snapshot));
  chk('the snapshot carries a generated date', /^\d{4}-\d{2}-\d{2}$/.test(snapshot.generated));
  chk('every claim carries a date not after the snapshot', snapshot.claims.every((c) => c.date <= snapshot.generated));
  chk('every claim names a subject the corpus block counts',
      snapshot.claims.every((c) => ('n_' + c.subject) in snapshot.corpus));
  chk('every claim quotes a sentence that contains its own number',
      snapshot.claims.every((c) => c.sentence.replace(/,/g, '').includes(String(c.number))));

  console.log('\nThe two engines');
  const a = measureA(snapshot), b = measureB(snapshot);
  chk('the two engines agree on every value', agree(a, b));
  chk('  and on the claim count', a.n_claims === b.n_claims);
  chk('  and on how many are still true', a.n_true_now === b.n_true_now);

  console.log('\nThe measurement');
  chk('the claim count matches the snapshot', a.n_claims === snapshot.claims.length);
  chk('true plus false accounts for every claim', a.n_true_now + a.n_false_now === a.n_claims);
  chk('the drift list is exactly the false ones', a.drift.length === a.n_false_now);
  chk('drift is sorted by gap descending',
      a.drift.every((d, i) => i === 0 || a.drift[i - 1].gap > d.gap
        || (a.drift[i - 1].gap === d.gap && a.drift[i - 1].slug <= d.slug)));
  chk('every drift row states a gap that is current minus stated',
      a.drift.every((d) => d.gap === d.current - d.stated));
  chk('ages are computed from the snapshot dates, not the clock',
      a.drift.every((d) => {
        const p = (s) => Date.UTC(+s.slice(0, 4), +s.slice(5, 7) - 1, +s.slice(8, 10));
        return d.days_old === Math.round((p(snapshot.generated) - p(d.date)) / 86400000);
      }));
  chk('the worst drift is the largest gap', a.worst === null || a.worst.gap === Math.max(...a.drift.map((d) => d.gap)));

  console.log('\nThe control the layer argues for');
  chk('the snapshot records date-scoped sentences that cannot rot', snapshot.excluded_counts.scoped > 0);
  chk('  and keeps samples of them, so the filter can be argued with',
      snapshot.excluded_samples.scoped.length > 0);
  chk('  and records the subset exclusions too', snapshot.excluded_counts.subset > 0);
  chk('every scoped sample really carries a date-scoping phrase',
      snapshot.excluded_samples.scoped.every((e) =>
        /(as of|at the time of writing|before this page|on \d{4}-\d{2}-\d{2}|in (january|february|march|april|may|june|july|august|september|october|november|december)|by \d{4}|as at)/i.test(e.sentence)));

  console.log('\nThe shipped page');
  chk('the page states the claim count', html.includes(String(a.n_claims)));
  // The page draws the drift table from the snapshot in JavaScript, so the slug is not in
  // the HTML source. What IS in the source, and what matters, is that the page names the
  // data file it draws from and does not hard-code a layer name that could go stale.
  chk('the page fetches the snapshot rather than hard-coding the drift',
      html.includes('corpus-claims.json') || readFileSync(join(ROOT, 'public/strata/the-sentences-that-rot/instrument.js'), 'utf8').includes('corpus-claims.json'));
  chk('the page carries the check heading', /id="the-check"/.test(html));
  chk('the page names this verifier', html.includes('verify.mjs'));
  chk('the page ends with </body> then </html>', /<\/body>\s*<\/html>\s*$/.test(html));
  chk('the page carries no em dash', !html.includes('—'));
  chk('the page does not claim the half-life is a measurement',
      !/half[- ]life of \d+ days\b/i.test(html) || /ceiling|bound|youngest/i.test(html));

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

// Negative controls. Each asserts its own corruption landed before it is allowed to count,
// because a control that mutates nothing and passes is the defect this wave kept finding.
const clone = (x) => JSON.parse(JSON.stringify(x));
let red = 0, total = 0;
function control(name, landed, wentRed) {
  total++;
  if (!landed) { console.log('  INERT (bad control, mutated nothing): ' + name); return; }
  if (wentRed) { red++; console.log('  red  ' + name); }
  else console.log('  STILL GREEN (bad control): ' + name);
}

{ // a claim's stated number bent to match the corpus should flip it to true
  const s = clone(snapshot);
  const target = s.claims.find((c) => c.number !== s.corpus['n_' + c.subject]);
  const before = target.number;
  target.number = s.corpus['n_' + target.subject];
  const m = measureA(s);
  control('a claim bent to match the corpus stops being drift',
    target.number !== before, m.n_false_now < measureA(snapshot).n_false_now);
}
{ // moving the generated date must move every age
  const s = clone(snapshot);
  const before = s.generated;
  s.generated = '2027-01-01';
  const m = measureA(s);
  control('moving the snapshot date moves every age',
    s.generated !== before,
    m.drift.every((d, i) => d.days_old !== measureA(snapshot).drift[i].days_old));
}
{ // the two engines must actually be compared, not assumed equal
  const s = clone(snapshot);
  s.corpus.n_strata = s.corpus.n_strata + 1;
  control('perturbing the corpus count changes both engines the same way',
    s.corpus.n_strata !== snapshot.corpus.n_strata,
    !agree(measureA(s), measureA(snapshot)) && agree(measureA(s), measureB(s)));
}
{ // scrubbing the claim count from the page must break the page check
  const bad = html.split(String(measureA(snapshot).n_claims)).join('99999');
  control('scrubbing the claim count from the page breaks the page check',
    bad !== html, !bad.includes('>' + measureA(snapshot).n_claims + '<'));
}
console.log(`\n  ${red} of ${total} controls went red as required.`);
process.exit(red === total ? 0 : 1);
