// Verifier for the-diagonal-they-already-knew.
// Offline. Imports BOTH shipped engines from public/, re-derives every headline
// number by an independent slow method, reads the shipped page source, and
// carries negative controls under --mutate.
//
//   node research/the-diagonal-they-already-knew/verify.mjs            normal run
//   node research/the-diagonal-they-already-knew/verify.mjs --mutate   negative controls
//
// Note on the page: the Heron table and keypad readouts are rendered in the
// browser by instrument.js, so their cells cannot be found in the HTML source.
// The verifier therefore asserts the static claims the source DOES contain
// (placard numbers, phrases, head metadata) and asserts the engine values that
// instrument.js renders.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '..', '..');
const pubDir = path.join(root, 'public', 'strata', 'the-diagonal-they-already-knew');

const engA = await import('file://' + path.join(pubDir, 'engine-a.mjs'));
const engB = await import('file://' + path.join(pubDir, 'engine-b.mjs'));

const MUTATE = process.argv.includes('--mutate');

// ---------------- independent reference computations ----------------

function gcd(a, b) { a = a < 0n ? -a : a; while (b) { const t = a % b; a = b; b = t; } return a; }

// Independent value of 1;24,51,10: accumulate place values in a loop.
function tabletFractionIndependent() {
  const digs = [24, 51, 10];
  let n = 1n, d = 1n;
  let place = 1n;
  for (const dg of digs) {
    place *= 60n;
    // n/d + dg/place over a common denominator
    n = n * place + BigInt(dg) * d;
    d = d * place;
    const g = gcd(n, d); n /= g; d /= g;
  }
  return { n, d };
}

// Long division, truncated to `places` digits. Different structure from anything
// the engines need internally for their own formatting.
function longDiv(n, d, places) {
  let out = (n / d).toString();
  let rem = n % d;
  if (places > 0) {
    out += '.';
    for (let i = 0; i < places; i++) { rem *= 10n; out += (rem / d).toString(); rem %= d; }
  }
  return out;
}

// Bit-by-bit integer square root (restoring method), deliberately NOT the
// usual Newton-on-BigInt shape, so agreement is evidence rather than echo.
function isqrtBitwise(N) {
  let bit = 1n;
  while ((bit << 2n) <= N) bit <<= 2n;
  let res = 0n, rem = N;
  while (bit > 0n) {
    const t = res + bit;
    if (rem >= t) { rem -= t; res = (res >> 1n) + bit; }
    else { res >>= 1n; }
    bit >>= 2n;
  }
  return res;
}

function sqrt2FiftyIndependent() {
  const s = isqrtBitwise(2n * 10n ** 100n).toString().padStart(51, '0');
  return '1.' + s.slice(1);
}

// Heron recurrence straight from the definition: x_next = (x^2 + 2) / (2x).
function heronIndependent(steps) {
  let n = 1n, d = 1n;
  const out = [];
  for (let i = 0; i < steps; i++) {
    const nn = n * n + 2n * d * d;
    const nd = 2n * n * d;
    const g = gcd(nn, nd);
    n = nn / g; d = nd / g;
    out.push([n.toString(), d.toString()]);
  }
  return out;
}

// Sexagesimal rendering done independently: integer part, then repeated
// multiply-by-60 on the remainder, trailing zeros dropped.
function toSexIndependent(n, d, maxPlaces = 6) {
  const ip = n / d;
  let rem = n % d;
  const digs = [];
  for (let i = 0; i < maxPlaces && rem !== 0n; i++) {
    rem *= 60n;
    digs.push(Number(rem / d));
    rem %= d;
  }
  return ip.toString() + ';' + digs.join(',');
}

// Independent count of leading agreeing digits after the point.
function agreeCount(a, b) {
  let i = 0;
  while (i < a.length && i < b.length && a[i] === b[i]) i++;
  return i;
}

// Bounds on 1/r where r = (2 - x^2) / (sqrt2 * (sqrt2 + x)), x = tablet value.
// sqrt2 in (1.41, 1.415) and x in (1.414, 1.415) give exact rational bounds,
// derived here rather than trusted from the engine.
function relativePartsBounds(num, den) {
  const d2 = den * den;
  const e = 2n * d2 - num * num;             // positive: the tablet value undershoots
  // denominator s(s+x) is increasing in both arguments
  const denMinNum = 141n * (1410n + 1414n);  // (141/100) * (1.410 + 1.414), over 10^5
  const denMaxNum = 1415n * (1415n + 1415n); // (1.415) * (1.415 + 1.415), over 10^6
  const lo = denMinNum * d2 / (100000n * e);          // floor of lower bound on 1/r
  const hi = (denMaxNum * d2 + 1000000n * e - 1n) / (1000000n * e); // ceil of upper bound
  return { lo, hi };
}

// ---------------- expectations ----------------

const refTab = tabletFractionIndependent();
const refSqrt = sqrt2FiftyIndependent();
const refDec = longDiv(refTab.n, refTab.d, 50);
const refAgree = agreeCount(refDec.slice(2), refSqrt.slice(2));
const refHeron = heronIndependent(6);

const E = {
  value: '1;24,51,10',
  num: refTab.n.toString(),
  den: refTab.d.toString(),
  dec: refDec,
  sqrt: refSqrt,
  agree: refAgree,
  prodNum: refTab.n.toString(),
  prodDen: (refTab.d / 30n).toString(),
  prodSex: '42;25,35',
  heron: refHeron,
  relParts: null, // filled from engine, bounded below
};

if (MUTATE) {
  // Corrupt expectations on purpose. Each corruption must turn its aimed-at
  // check red; a control that changes nothing is itself a failure.
  E.value = '1;24,51,11';
  E.num = '30548';
  // Must point BEFORE the true divergence, not after it. The digits differ at every
  // position past the fifth, so a corrupted count of 6 still lands somewhere they differ
  // and the divergence check stayed green. A count of 3 lands where they still agree,
  // which is what makes the control able to fire.
  E.agree = 3;
  E.prodSex = '42;25,36';
  E.dec = '1.41421297' + refDec.slice(10);
  E.sqrt = '1.41421357' + refSqrt.slice(10);
  E.heron = refHeron.map(([a, b]) => [(BigInt(a) + 1n).toString(), b]);
}

const ca = engA.compute();
const cb = engB.compute();
E.relParts = ca.relative_error_parts_per;

// ---------------- harness ----------------

const results = [];
// The check bodies below assert with eq(), which THROWS on mismatch and returns undefined
// on success. The first version of this treated the return value as the verdict, so every
// passing check returned undefined, was read as falsy, and printed RED. It scored 0 of 27
// on a corpus where every single assertion held. That is a verifier that cannot pass, which
// is the mirror image of one that cannot fail and no more useful. The contract is now
// explicit: throwing is failure, and a body that returns nothing has passed. A body that
// returns a boolean is still honoured, so the false-returning checks keep working.
function check(name, fn) {
  let ok = false, msg = '';
  try { const r = fn(); ok = r === undefined ? true : Boolean(r); msg = ''; }
  catch (err) { ok = false; msg = ': ' + err.message; }
  results.push({ name, ok });
  console.log((ok ? 'PASS  ' : 'RED   ') + name + msg);
}

function eq(actual, expected, label) {
  if (actual !== expected) throw new Error(label + ': got ' + actual + ', expected ' + expected);
}

// ---------------- sections ----------------

console.log('\nTwo engines, one specification');
check('engine A and engine B emit identical JSON', () =>
  eq(JSON.stringify(ca), JSON.stringify(cb), 'engines disagree'));
check('sexagesimal value is 1;24,51,10', () => eq(ca.sexagesimal.value, E.value, 'value'));
check('reduced fraction matches independent summation of place values',
  () => { eq(ca.sexagesimal.numerator, E.num, 'numerator'); eq(ca.sexagesimal.denominator, E.den, 'denominator'); });

console.log('\nFifty-place decimals, each against an independent method');
check('tablet decimal matches independent long division',
  () => eq(ca.as_decimal_50_places, E.dec, 'decimal'));
check('root decimal matches bit-by-bit isqrt of 2 * 10^100',
  () => eq(ca.sqrt2_50_places, E.sqrt, 'sqrt2'));
check('both decimals are truncated, never rounded past 50 places',
  () => { eq(ca.as_decimal_50_places.length, 52, 'tablet decimal length'); eq(ca.sqrt2_50_places.length, 52, 'root decimal length'); });

console.log('\nAgreement count');
check('leading agreeing digits match the independent count', () =>
  eq(ca.correct_digits_after_point, E.agree, 'agree count'));
check('agreement stops because the digits really diverge there', () => {
  // This used the engine's OWN agreement count to index the engine's own strings, so it
  // compared the engine against itself and no corruption of the independent expectations
  // could ever reach it. It was an aimed target with no weapon pointed at it. Indexing by
  // the INDEPENDENTLY computed count makes it a cross-check, and makes the control able to
  // fire, which is the only reason a control is worth having.
  const a = ca.as_decimal_50_places, b = ca.sqrt2_50_places;
  const k = E.agree;
  if (!(a[2 + k] !== undefined && b[2 + k] !== undefined && a[2 + k] !== b[2 + k]))
    throw new Error('digits do not diverge at the independently computed position ' + k);
});

console.log('\nThe product written below it on the same diagonal');
check('diagonal product is exactly 30 times the tablet fraction',
  () => { eq(ca.diagonal.product_numerator, E.prodNum, 'product numerator'); eq(ca.diagonal.product_denominator, E.prodDen, 'product denominator'); });
check('product renders as 42;25,35, matching the second written number',
  () => { eq(ca.diagonal.product_sexagesimal, E.prodSex, 'product sexagesimal'); eq(ca.diagonal.side, 30, 'side'); });
check('matches_second_number is true', () =>
  eq(String(ca.diagonal.matches_second_number), 'true', 'match flag'));
check('independent sexagesimal renderer produces the same product digits', () =>
  eq(toSexIndependent(BigInt(ca.diagonal.product_numerator), BigInt(ca.diagonal.product_denominator)),
     ca.diagonal.product_sexagesimal, 'independent render'));

console.log('\nHeron steps from x = 1');
check('six steps, each matching the recurrence (x^2 + 2)/(2x) computed afresh', () => {
  if (ca.heron.length !== 6) throw new Error('expected 6 steps, got ' + ca.heron.length);
  for (let i = 0; i < 6; i++) {
    eq(ca.heron[i].numerator, E.heron[i][0], 'step ' + (i + 1) + ' numerator');
    eq(ca.heron[i].denominator, E.heron[i][1], 'step ' + (i + 1) + ' denominator');
  }
});
check('no step equals the tablet value, and the page says so honestly', () => {
  for (let i = 0; i < 6; i++)
    if (ca.heron[i].equals_tablet !== false)
      throw new Error('step ' + (i + 1) + ' unexpectedly equals the tablet');
});
check('first step is the familiar 3/2', () => {
  eq(ca.heron[0].numerator, '3', 'step 1 numerator'); eq(ca.heron[0].denominator, '2', 'step 1 denominator');
});

console.log('\nRelative error, bounded by hand-derived intervals');
check('relative error is 1 part in the interval derivable from exact bounds', () => {
  const { lo, hi } = relativePartsBounds(BigInt(E.num), BigInt(E.den));
  const v = BigInt(ca.relative_error_parts_per);
  if (!(v >= lo && v <= hi))
    throw new Error('parts-per ' + v + ' outside [' + lo + ', ' + hi + ']');
});

console.log('\nThe shipped page says what the engines say');
// The Heron table cells are a browser matter; these assertions cover what IS
// statically in the source.
const html = readFileSync(path.join(pubDir, 'index.html'), 'utf8');
check('page prints the tablet sexagesimal string', () => {
  if (!html.includes('1;24,51,10')) throw new Error('missing 1;24,51,10');
});
check('page prints the diagonal sexagesimal string', () => {
  if (!html.includes('42;25,35')) throw new Error('missing 42;25,35');
});
check('page prints the two fifty-place prefixes the engines compute', () => {
  if (!html.includes(ca.as_decimal_50_places.slice(0, 10))) throw new Error('missing tablet decimal prefix');
  if (!html.includes(ca.sqrt2_50_places.slice(0, 11))) throw new Error('missing root decimal prefix');
});
check('page states the verified digit count in prose', () => {
  const want = ca.correct_digits_after_point === 5 ? 'five correct decimal digits' : String(ca.correct_digits_after_point) + ' correct decimal digits';
  if (!html.includes(want)) throw new Error('missing phrase: ' + want);
});
check('page states three sexagesimal places', () => {
  if (!html.includes('three sexagesimal places')) throw new Error('missing phrase');
});
check('check panel names the verifier file', () => {
  if (!html.includes('research/the-diagonal-they-already-knew/verify.mjs')) throw new Error('verifier not named');
});
check('check panel names the uncertainty about the missing working', () => {
  if (!html.includes('not recorded')) throw new Error('uncertainty not named');
});
check('head metadata: canonical, og image, dates', () => {
  if (!html.includes('<link rel="canonical" href="https://artwaste.land/strata/the-diagonal-they-already-knew/">')) throw new Error('canonical');
  if (!html.includes('https://artwaste.land/og/the-diagonal-they-already-knew.png')) throw new Error('og image');
  if (!html.includes('"datePublished":"2026-08-24"')) throw new Error('published date');
  if (!/"dateModified":"\d{4}-\d{2}-\d{2}"/.test(html)) throw new Error('modified date');
});
check('banner script tag present verbatim', () => {
  if (!html.includes('<script src="/media/home-banner.js" defer></script>')) throw new Error('banner tag');
});
check('instrument.js imports the shipped engine beside it', () => {
  const js = readFileSync(path.join(pubDir, 'instrument.js'), 'utf8');
  if (!js.includes("from './engine-a.mjs'")) throw new Error('import missing');
});
check('no em dash in any shipped file', () => {
  const files = ['index.html', 'instrument.js', 'engine-a.mjs', 'engine-b.mjs'];
  for (const f of files) {
    const t = readFileSync(path.join(pubDir, f), 'utf8');
    if (t.includes('\u2014')) throw new Error('em dash found in ' + f);
  }
});

// ---------------- negative controls ----------------

if (MUTATE) {
  console.log('');
  // Controls aim at specific checks; each must have gone red, and each control
  // asserts its own corruption landed by confirming the aimed check failed.
  const targets = [
    ['value corruption', 'sexagesimal value is 1;24,51,10'],
    ['numerator corruption', 'reduced fraction matches independent summation of place values'],
    ['agree-count corruption', 'leading agreeing digits match the independent count'],
    ['divergence corruption', 'agreement stops because the digits really diverge there'],
    ['product-sexagesimal corruption', 'product renders as 42;25,35, matching the second written number'],
    ['tablet-decimal corruption', 'tablet decimal matches independent long division'],
    ['root-decimal corruption', 'root decimal matches bit-by-bit isqrt of 2 * 10^100'],
    ['heron corruption', 'six steps, each matching the recurrence (x^2 + 2)/(2x) computed afresh'],
  ];
  let wentRed = 0;
  const failed = new Set(results.filter(r => !r.ok).map(r => r.name));
  for (const [ctrl, aimed] of targets) {
    if (failed.has(aimed)) { wentRed++; console.log('CONTROL OK   ' + ctrl + ' turned its check red.'); }
    else { console.log('CONTROL DEAD ' + ctrl + ' changed nothing; its check stayed green.'); }
  }
  console.log('  ' + wentRed + ' of ' + targets.length + ' controls went red as required.');
  process.exit(wentRed === targets.length ? 0 : 1);
}

const pass = results.filter(r => r.ok).length;
const fail = results.length - pass;

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