// Verifier for the odd-perfect-number sieve layer.
// Runs offline: node research/the-shape-of-a-thing-nobody-has-found/verify.mjs
// Negative controls: node research/the-shape-of-a-thing-nobody-has-found/verify.mjs --mutate

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

const HERE = dirname(fileURLToPath(import.meta.url));
const PUB = join(HERE, '..', '..', 'public', 'strata', 'the-shape-of-a-thing-nobody-has-found');

const A = await import(join(PUB, 'engine-a.mjs'));
const B = await import(join(PUB, 'engine-b.mjs'));

let pass = 0, fail = 0;

// The specification named eulerFormOk(q, a) without pinning its return SHAPE, so one engine
// returns a boolean and the other an object carrying the reason. Both obeyed the text. The
// checks read the verdict out of either rather than insisting on one spelling, and the gap
// is recorded against the specification rather than against either author.
const truthy = (v) => (v && typeof v === 'object' && 'ok' in v) ? Boolean(v.ok) : Boolean(v);

function check(name, fn) {
  try { fn(); console.log('ok   ' + name); pass++; }
  catch (e) { console.log('RED  ' + name + ' :: ' + e.message); fail++; }
}
function assert(cond, msg) { if (!cond) throw new Error(msg); }
function eq(a, b, msg) { assert(Object.is(a, b) || String(a) === String(b), msg + ' (got ' + a + ', want ' + b + ')'); }

// Slow, obviously-correct reference implementations, deliberately naive.
function sigmaSlow(n) { // plain loop over all divisors
  let s = 0;
  for (let d = 1; d <= n; d++) if (n % d === 0) s += d;
  return s;
}
function gcd(a, b) { while (b) { const t = a % b; a = b; b = t; } return a; }
function fracLess(a, b) { return a.num * b.den < b.num * a.den; } // BigInt fields

let Aout, Bout;
try { Aout = A.compute(); } catch (e) { console.log('RED  engine-a compute() threw: ' + e.message); process.exit(1); }
try { Bout = B.compute(); } catch (e) { console.log('RED  engine-b compute() threw: ' + e.message); process.exit(1); }

console.log('\n== Agreement of the two independent engines ==');
// euler_form_examples is excluded from the field-by-field comparison on purpose: the
// specification asked for "examples" without saying which, so the two authors chose
// different illustrative pairs and both obeyed the text. That is a defect in the
// specification, not in either engine, and the page withholds the examples rather than
// picking a winner.
for (const key of Object.keys(Aout)) {
  if (key === 'euler_form_examples') continue;
  check('engines agree on ' + key, () =>
    eq(JSON.stringify(Aout[key]), JSON.stringify(Bout[key]), 'field mismatch'));
}

console.log('\n== Anchors against slow brute force ==');
check('perfect numbers up to 10000 are exactly 6, 28, 496, 8128', () => {
  eq(JSON.stringify(Aout.perfect_up_to_10000.map((x) => x.n)), JSON.stringify([6, 28, 496, 8128]), 'census list');
});
check('each census entry has the right Mersenne form', () => {
  const want = [{ n: 6, p: 2 }, { n: 28, p: 3 }, { n: 496, p: 5 }, { n: 8128, p: 7 }];
  Aout.perfect_up_to_10000.forEach((x, i) => {
    eq(x.p, want[i].p, 'p for ' + x.n);
    eq(x.mersenne, 2 ** want[i].p - 1, 'mersenne for ' + x.n);
    assert((2 ** (want[i].p - 1)) * (2 ** want[i].p - 1) === x.n, 'Euclid form rebuild for ' + x.n);
  });
});
check('sigma(8128) by engine equals slow divisor loop', () =>
  eq(Number(A.sigma(8128)), sigmaSlow(8128), 'sigma(8128)'));
check('sigma(945) by engine equals slow divisor loop', () =>
  eq(Number(A.sigma(945)), sigmaSlow(945), 'sigma(945)'));
check('abundancy(945) equals 1920/945 and exceeds 2', () => {
  // The specification did not say whether to reduce, and 1920/945 and 128/63 are the same
  // rational. Asserting one spelling tested a formatting choice, so this asserts the value.
  const a = A.abundancy(945);
  if (a.num * 945n !== 1920n * a.den) throw new Error('not equal to 1920/945');
  if (!(a.num > 2n * a.den)) throw new Error('does not exceed 2');
});
check('first odd abundant number is 945 (confirmed by slow scan)', () => {
  let first = null;
  for (let n = 1; n <= 2000; n += 2) {
    if (sigmaSlow(n) > 2 * n) { first = n; break; }
  }
  eq(first, 945, 'first odd abundant by brute force');
  eq(Aout.first_odd_abundant, 945, 'engine value');
});

console.log('\n== Independent recomputation of the census statistics ==');
// Slow full scan of the odd range, fraction comparisons throughout.
let bestBelow = null, bestAbove = null, nAbundant = 0;
for (let n = 1; n < 200000; n += 2) {
  const s = sigmaSlow(n);
  const f = { num: BigInt(s), den: BigInt(n) };
  const g = gcd(s, n);
  if ((s * 2) === 0) continue; // unreachable, keeps the shape explicit
  const cmp = f.num - 2n * f.den;
  if (cmp < 0n) {
    nAbundant += 0;
    if (!bestBelow || fracLess(bestBelow.f, f)) { bestBelow = { n: n, s: s, f: { num: f.num / BigInt(g), den: f.den / BigInt(g) } }; }
  } else if (cmp > 0n) {
    if (!bestAbove || fracLess(f, bestAbove.f)) { bestAbove = { n: n, s: s, f: { num: f.num / BigInt(g), den: f.den / BigInt(g) } }; }
  } else {
    nAbundant++;
  }
  if (s > 2 * n) nAbundant++;
}
// Fix the double-count above: recount cleanly.
nAbundant = 0;
for (let n = 1; n < 200000; n += 2) if (sigmaSlow(n) > 2 * n) nAbundant++;

check('closest approach from below matches the slow scan exactly', () => {
  eq(Aout.closest_below.n, bestBelow.n, 'n below');
  eq(Aout.closest_below.abundancy_num, bestBelow.f.num.toString(), 'num below');
  eq(Aout.closest_below.abundancy_den, bestBelow.f.den.toString(), 'den below');
});
check('closest approach from above matches the slow scan exactly', () => {
  eq(Aout.closest_above.n, bestAbove.n, 'n above');
  eq(Aout.closest_above.abundancy_num, bestAbove.f.num.toString(), 'num above');
  eq(Aout.closest_above.abundancy_den, bestAbove.f.den.toString(), 'den above');
});
check('count of odd abundant numbers below 200000 matches the slow scan', () =>
  eq(Aout.n_odd_abundant, nAbundant, 'odd abundant count'));
check('odd abundant count is strictly between the trivial bounds 945 and 100000', () => {
  assert(Aout.n_odd_abundant > 0 && Aout.n_odd_abundant < 100000, 'count outside sane interval');
});
check('histogram covers exactly the 100000 odd candidates', () => {
  const total = Object.values(Aout.abundancy_histogram).reduce((a, b) => a + b, 0);
  eq(total, 100000, 'histogram total');
});
check('every histogram bucket key is a two-decimal string', () => {
  // The first version demanded the buckets be CONTIGUOUS. They are not, and should not be:
  // no odd number has an abundancy between 1 and 1.01, so that bucket is legitimately
  // absent. Demanding contiguity asserted a property the data does not have.
  for (const k of Object.keys(Aout.abundancy_histogram)) {
    if (!/^[0-9]+[.][0-9][0-9]$/.test(k)) throw new Error('bad bucket key ' + k);
  }
});
check('3, 5, 7 exclusion count equals the direct count of odd multiples of 105', () => {
  // Computed rather than banded: 105 is odd, so its odd multiples are 105 times an odd
  // number. The first version used a guessed sanity band in place of the count.
  let n = 0;
  for (let k = 1; 105 * k <= Aout.odd_range; k += 2) n++;
  if (Aout.three_five_seven_excluded_count !== n) {
    throw new Error('got ' + Aout.three_five_seven_excluded_count + ', direct count ' + n);
  }
});
check('odd_range is 200000', () => eq(Aout.odd_range, 200000, 'range'));

console.log('\n== Euler form predicate ==');
check('eulerFormOk accepts (5,1) and (13,5)', () => {
  assert(truthy(A.eulerFormOk(5, 1)) === true, '(5,1)');
  assert(truthy(A.eulerFormOk(13, 5)) === true, '(13,5)');
  assert(truthy(B.eulerFormOk(5, 1)) === true, '(5,1) engine-b');
});
check('eulerFormOk rejects bad congruences', () => {
  assert(truthy(A.eulerFormOk(3, 1)) === false, 'q=3 mod 4');
  assert(truthy(A.eulerFormOk(5, 3)) === false, 'a=3 mod 4');
  assert(truthy(A.eulerFormOk(17, 2)) === false, 'a=2 mod 4');
  assert(truthy(B.eulerFormOk(3, 1)) === false, 'q=3 engine-b');
});

console.log('\n== The shipped page ==');
const htmlPath = join(PUB, 'index.html');
const html = readFileSync(htmlPath, 'utf8');
// The closest-approaches table and the histogram bars are rendered by
// instrument.js at run time, so their cells are a browser matter. What the
// source CAN be held to is the static text: the placard numbers, the dek,
// the check-panel claims, and the structural rules.
check('page is free of em dashes (U+2014)', () =>
  assert(!html.includes('\u2014'), 'em dash found'));
check('page mentions the census results 6, 28, 496, 8128', () => {
  for (const s of ['6', '28', '496', '8128']) assert(html.includes(s), 'missing ' + s);
});
check('page states the first odd abundant number 945 and the range 200000', () => {
  assert(html.includes('945'), 'missing 945');
  assert(html.includes('200000'), 'missing 200000');
});
check('dek numbers all appear in the body text', () => {
  for (const s of ['10000', '100000', '200000']) assert(html.includes(s), 'dek number missing from page: ' + s);
});
check('canonical URL is exact', () =>
  assert(html.includes('<link rel="canonical" href="https://artwaste.land/strata/the-shape-of-a-thing-nobody-has-found/">'), 'canonical'));
check('fonts load only from the site itself', () =>
  assert(html.includes('<link rel="stylesheet" href="/fonts/fonts.css">'), 'fonts.css link'));
check('og image points at the site, sized 1200x630', () => {
  assert(html.includes('https://artwaste.land/og/the-shape-of-a-thing-nobody-has-found.png'), 'og image');
  assert(html.includes('1200') && html.includes('630'), 'og dimensions');
});
check('JSON-LD carries both dates as 2026-08-24', () => {
  assert(html.split('"datePublished": "2026-08-24"').length === 2, 'datePublished');
  assert(html.split('"dateModified": "2026-08-24"').length === 2, 'dateModified');
});
check('the only inline script is the JSON-LD, and every other is same-origin', () => {
  // Pinning an exact script-tag count breaks the moment the site's chrome injectors add
  // theirs, which they legitimately do. The honest property is that nothing is inlined
  // except the structured data and no script comes from another origin.
  const inline = (html.match(/<script(?![^>]*[ ]src=)[^>]*>/g) || []);
  const bad = inline.filter((t) => t.indexOf('application/ld+json') === -1);
  if (bad.length) throw new Error(bad.length + ' inline script(s) that are not JSON-LD');
  const srcs = (html.match(/<script[^>]*[ ]src="[^"]+"/g) || []).map((t) => t.split('src="')[1].slice(0, -1));
  const off = srcs.filter((u) => /^https?:/i.test(u));
  if (off.length) throw new Error('off-origin script: ' + off[0]);
});
check('home banner snippet is verbatim', () =>
  assert(html.includes('<script src="/media/home-banner.js" defer></script>'), 'banner'));
check('file closes with </body> then </html>', () => {
  assert(html.trimEnd().endsWith('</html>'), 'closing html');
  const idxBody = html.lastIndexOf('</body>');
  const idxHtml = html.lastIndexOf('</html>');
  assert(idxBody !== -1 && idxBody < idxHtml, 'body before html close');
});
check('check panel names the verifier and separates computed from cited', () => {
  assert(html.includes('verify.mjs'), 'verifier named');
  assert(html.includes('NOT'), 'explicitly-not section');
  assert(html.includes('Ochem and Rao'), 'bound citation');
  assert(html.includes('Nielsen'), 'citation 2');
});
check('accessibility: labelled input, live statuses, focus ring, reduced-motion guard', () => {
  assert(html.includes('for="odd-input"'), 'label');
  assert((html.match(/role="status"/g) || []).length >= 2, 'live regions');
  assert(html.includes('prefers-reduced-motion'), 'reduced motion');
  assert(html.includes(':focus-visible'), 'focus ring');
});
check('instrument imports the shipped engine-a', () => {
  const js = readFileSync(join(PUB, 'instrument.js'), 'utf8');
  assert(js.includes("from './engine-a.mjs'"), 'import path');
  assert(js.includes('eulerFormOk'), 'uses the predicate');
  assert(!js.includes('\u2014'), 'em dash in instrument');
});

console.log('\n== Negative controls ==');
if (process.argv.includes('--mutate')) {
  let red = 0, total = 0;
  function control(name, land, probe) {
    total++;
    try {
      land(); // throws if the corruption did not actually land
      try { probe(); }
      catch { red++; return; }
      console.log('BAD  ' + name + ' stayed green');
    } catch (e) { console.log('BAD  ' + name + ' corruption failed to land: ' + e.message); }
  }
  control('tampered census goes red', () => {
    var c = JSON.parse(JSON.stringify(Aout));
    c.perfect_up_to_10000[3].n = 8127;
    assert(JSON.stringify(c) !== JSON.stringify(Aout), 'landing');
    globalThis.__mut = c;
  }, () => eq(globalThis.__mut.perfect_up_to_10000[3].n, 8128, 'anchor'));
  control('engine disagreement goes red', () => {
    var c = JSON.parse(JSON.stringify(Bout));
    c.n_odd_abundant += 1;
    assert(c.n_odd_abundant !== Bout.n_odd_abundant, 'landing');
    globalThis.__mutB = c; globalThis.__origB = Bout; Bout = c;
  }, () => eq(JSON.stringify(Aout.n_odd_abundant), JSON.stringify(Bout.n_odd_abundant), 'agree'));
  Bout = globalThis.__origB;
  // The first version replaced only the FIRST 945 and then asked whether the string 945
  // still appeared anywhere. It did, in the other occurrences, so the control mutated the
  // page and then failed to notice. Replace every occurrence, and assert on the absence.
  control('altered page text goes red', () => {
    var h = html.split('945').join('946');
    assert(h !== html && !h.includes('945'), 'landing');
    globalThis.__mutH = h;
  }, () => assert(globalThis.__mutH.includes('945'), '945 present'));
  control('injected em dash goes red', () => {
    var h = html.replace('</title>', ' \u2014</title>');
    assert(h.includes('\u2014'), 'landing');
    globalThis.__mutD = h;
  }, () => assert(!globalThis.__mutD.includes('\u2014'), 'no em dash'));
  // The first version mutated a CLONE and then re-read the ORIGINAL to ask whether anything
  // had gone wrong, so of course nothing had. Mutating a copy and checking the source is the
  // most common way a control certifies nothing at all. The mutated object is now the thing
  // that gets checked.
  control('broken histogram goes red', () => {
    var c = JSON.parse(JSON.stringify(Aout));
    const k0 = Object.keys(c.abundancy_histogram)[0];
    c.abundancy_histogram[k0] += 1;
    assert(c.abundancy_histogram[k0] !== Aout.abundancy_histogram[k0], 'landing');
    globalThis.__mutHist = c;
  }, () => {
    const t = Object.values(globalThis.__mutHist.abundancy_histogram).reduce((a, b) => a + b, 0);
    const want = Object.values(Aout.abundancy_histogram).reduce((a, b) => a + b, 0);
    eq(t, want, 'total');
  });
  console.log('  ' + red + ' of ' + total + ' controls went red as required.');
  assert(red === total, 'every control must go red');
} else {
  console.log('(run with --mutate for the negative controls)');
}

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

