#!/usr/bin/env node
import fs from 'node:fs';
import vm from 'node:vm';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const pagePath = path.join(root, 'public/strata/chaitin-omega/index.html');
let checks = 0;
let failures = 0;

function show(ok, name, detail = '') {
  checks++;
  const mark = ok ? 'PASS' : 'FAIL';
  console.log(`${mark} ${String(checks).padStart(3, '0')}  ${name}${detail ? `  ${detail}` : ''}`);
  if (!ok) failures++;
}

function equal(actual, expected, name) {
  const ok = actual === expected;
  show(ok, name, ok ? String(actual) : `expected ${String(expected)}, received ${String(actual)}`);
}

function truth(value, name, detail = '') {
  show(Boolean(value), name, detail);
}

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

function fraction(n, d) {
  if (d < 0n) [n, d] = [-n, -d];
  const g = gcd(n, d);
  return { n: n / g, d: d / g };
}

function plus(a, b) {
  return fraction(a.n * b.d + b.n * a.d, a.d * b.d);
}

function compare(a, b) {
  const x = a.n * b.d;
  const y = b.n * a.d;
  return x < y ? -1 : x > y ? 1 : 0;
}

function floorAt(q, bits) {
  return (q.n << BigInt(bits)) / q.d;
}

function binaryAt(q, bits) {
  return floorAt(q, bits).toString(2).padStart(bits, '0').slice(-bits);
}

const lengths = Object.freeze([7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84]);
const halts = Object.freeze([1n, 1n, 3n, 8n, 50n, 311n, 1012n, 4382n, 19164n, 99785n, 515279n, 2559837n]);
const noHaltPrefixes = 402906842n;
const withHaltPrefixes = 1748380n;

function independentKraft(ls = lengths, hs = halts) {
  return hs.reduce((sum, h, i) => sum + h * (1n << BigInt(84 - ls[i])), 0n);
}

function independentTails(a = noHaltPrefixes, b = withHaltPrefixes, pow = 91, dataRatio = 63n, opcodeRatio = 81n) {
  // Assumed tail, not either complete source expression: first term sums the arXiv HALT-free series; second uses its printed reduced HALT term. See README.md.
  const base = 1n << BigInt(pow);
  const first = fraction(a * 64n, dataRatio * opcodeRatio * base);
  const second = fraction(b, dataRatio * base);
  return { first, second, total: plus(first, second) };
}

function independentCertificate(ls = lengths, hs = halts, a = noHaltPrefixes, b = withHaltPrefixes) {
  const lower = fraction(independentKraft(ls, hs), 1n << 84n);
  const tails = independentTails(a, b);
  const upper = plus(lower, tails.total);
  let common = 0;
  for (let bit = 1; bit <= 84; bit++) {
    if (floorAt(lower, bit) !== floorAt(upper, bit)) break;
    common = bit;
  }
  return { lower, upper, tails, common, prefix: binaryAt(lower, common) };
}

console.log('\nSOURCE DATA AND EQUATIONS');
equal(lengths.length, 12, 'twelve published length rows');
for (let i = 0; i < lengths.length; i++) {
  equal(lengths[i], 7 * (i + 1), `row ${i + 1} length is seven-bit aligned`);
}
const expectedHalts = ['1', '1', '3', '8', '50', '311', '1012', '4382', '19164', '99785', '515279', '2559837'];
for (let i = 0; i < halts.length; i++) {
  equal(halts[i].toString(), expectedHalts[i], `row ${i + 1} halting count matches Table 1`);
}
equal(noHaltPrefixes, 402906842n, 'HALT-free prefix count transcription');
equal(withHaltPrefixes, 1748380n, 'HALT-containing prefix count transcription');
equal(halts.at(-1), 2559837n, 'length-84 halting count');
truth(halts.every((h, i) => i === 0 || h >= halts[i - 1]), 'published counts are nondecreasing by row');

console.log('\nINDEPENDENT KRAFT AND CARRY ARITHMETIC');
const cert = independentCertificate();
equal(independentKraft(), 152324595200689294522077n, 'weighted 84-bit Kraft numerator');
equal(cert.lower.d, 19342813113834066795298816n, 'lower denominator is 2^84');
equal(binaryAt(cert.lower, 84), '000000100000010000011000100001101000111111001011101110100001000001111011011011011101', '84-bit lower approximation');
equal(cert.tails.first.n, 201453421n, 'first assumed residual term reduced numerator');
equal(cert.tails.first.d, 98706375319895242856409858048n, 'first assumed residual term reduced denominator');
truth(compare(cert.tails.first, fraction(1n, 1n)) < 0, 'first assumed residual term is below one');
truth(compare(cert.tails.second, fraction(1n, 1n)) < 0, 'second assumed residual term is below one');
equal(cert.tails.total.n, 6481914167n, 'combined reduced tail numerator');
equal(cert.tails.total.d, 3158604010236647771405115457536n, 'combined reduced tail denominator');
truth(cert.tails.total.n * (1n << 68n) < cert.tails.total.d, 'assumed tail is strictly below 2^-68');
truth(cert.tails.total.n * (1n << 69n) > cert.tails.total.d, 'tail is not below 2^-69');
truth(compare(cert.lower, cert.upper) < 0, 'lower endpoint precedes upper endpoint');
truth(compare(cert.upper, fraction(1n, 1n)) < 0, 'upper endpoint remains below one');
equal(cert.common, 64, 'largest common endpoint prefix has 64 bits');
equal(cert.prefix, '0000001000000100000110001000011010001111110010111011101000010000', 'conditional prefix matches the reported 64-bit prefix');
equal(binaryAt(cert.lower, 68).slice(64), '0111', 'four following lower digits are provisional 0111');
equal(floorAt(cert.lower, 64), floorAt(cert.upper, 64), 'endpoint floors agree at 64 bits');
truth(floorAt(cert.lower, 65) !== floorAt(cert.upper, 65), 'endpoint floors separate at 65 bits');
equal(floorAt(cert.lower, 64), 145268054199876112n, 'common 64-bit floor value');
equal(floorAt(cert.upper, 65) - floorAt(cert.lower, 65), 1n, 'one integer boundary lies between endpoints at bit 65');

console.log('\nPAGE STRUCTURE AND SHIPPED ENGINE COUPLING');
const html = fs.readFileSync(pagePath, 'utf8');
truth(html.startsWith('<!doctype html>'), 'page begins with HTML doctype');
truth(html.trimEnd().endsWith('</script>\n</body>\n</html>'), 'load-bearing closing tags are present');
truth(!html.includes(String.fromCodePoint(0x2014)), 'page contains no em dash character');
truth(html.includes('<link rel="canonical" href="https://artwaste.land/strata/chaitin-omega/"'), 'canonical URL is correct');
truth(html.includes('role="status" aria-live="polite"'), 'page contains a live status region');
truth(html.includes(':focus-visible'), 'page defines visible keyboard focus');
truth(html.includes('@media(prefers-reduced-motion:reduce)'), 'page guards reduced motion');
truth(!/(?:src|href)=["']https?:\/\/[^"']+["'][^>]*(?:stylesheet|script)/i.test(html), 'no third-party script or stylesheet request');
const engineMatch = html.match(/<script id="omega-engine">([\s\S]*?)<\/script>/);
truth(engineMatch, 'page engine script can be extracted');
const context = vm.createContext({ console });
vm.runInContext(engineMatch[1], context, { filename: 'shipped-omega-engine.js' });
const page = context.OmegaEngine;
truth(page && typeof page.certificate === 'function', 'shipped engine exports certificate function');
equal(Array.from(page.LENGTHS).join(','), lengths.join(','), 'page lengths equal verifier source data');
equal(Array.from(page.HALTS, String).join(','), halts.map(String).join(','), 'page halting counts equal verifier source data');
equal(page.PREFIX_NO_HALT, noHaltPrefixes, 'page HALT-free prefix count is coupled');
equal(page.PREFIX_WITH_HALT, withHaltPrefixes, 'page HALT-containing prefix count is coupled');
equal(page.kraftNumerator(), independentKraft(), 'page Kraft numerator equals independent engine');
const pageTail = page.tailParts();
equal(pageTail.a.n * cert.tails.first.d, cert.tails.first.n * pageTail.a.d, 'page first tail equals independent fraction');
equal(pageTail.b.n * cert.tails.second.d, cert.tails.second.n * pageTail.b.d, 'page second tail equals independent fraction');
equal(pageTail.total.n, cert.tails.total.n, 'page combined tail numerator');
equal(pageTail.total.d, cert.tails.total.d, 'page combined tail denominator');
const pageCert = page.certificate();
equal(pageCert.lower.n, cert.lower.n, 'page lower numerator equals independent engine');
equal(pageCert.lower.d, cert.lower.d, 'page lower denominator equals independent engine');
equal(pageCert.upper.n * cert.upper.d, cert.upper.n * pageCert.upper.d, 'page upper endpoint equals independent engine');
equal(pageCert.prefixLength, cert.common, 'page discovers independent common-prefix length');
equal(pageCert.prefix, cert.prefix, 'page discovers independent certified bits');

console.log('\nREGISTER MACHINE AND PREFIX INSTRUMENT');
const fleet = page.fleetPrograms();
equal(fleet.length, 2048, 'fleet contains every eleven-bit data word');
equal(new Set(fleet).size, 2048, 'all fleet inputs are distinct');
truth(fleet.every(p => /^[\x00-\x7f]+$/.test(p)), 'fleet source is seven-bit ASCII');
truth(fleet.every(p => p.endsWith(p.slice(-11)) && /^[01]{11}$/.test(p.slice(-11))), 'every fleet member carries eleven binary data characters');
const compiledFirst = page.compile(fleet[0]);
const compiledLast = page.compile(fleet.at(-1));
equal(compiledFirst.data, '00000000000', 'first data word is all zero');
equal(compiledLast.data, '11111111111', 'last data word is all one');
equal(compiledFirst.wireBits, compiledLast.wireBits, 'all fleet wire encodings have equal length');
equal(compiledFirst.wireBits % 7, 0, 'wire length is seven-bit aligned');
equal(compiledFirst.instructions.filter(i => i.op === '!').length, 11, 'program contains eleven READ instructions');
equal(compiledFirst.instructions.filter(i => i.op === '=').length, 11, 'program contains eleven equality instructions');
equal(compiledFirst.instructions.filter(i => i.op === '/').length, 11, 'program contains eleven optional DUMP steps');
equal(compiledFirst.instructions.filter(i => i.op === '%').length, 1, 'program contains one final HALT');
const audit = page.auditPrefixFree(fleet);
truth(audit.prefixFree, 'fleet wire encodings are prefix-free');
equal(audit.leaves, 2048, 'prefix audit sees 2,048 leaves');
equal(audit.patriciaNodes, 4095, 'derived Patricia node count for 2,048 leaves');
equal(audit.minBits, audit.maxBits, 'prefix audit confirms equal wire lengths');
const at0 = page.simulateFleet(0);
const at23 = page.simulateFleet(23);
const at24 = page.simulateFleet(24);
const at34 = page.simulateFleet(34);
const at4096 = page.simulateFleet(4096);
equal(at0.halted, 0, 'zero budget witnesses no halts');
equal(at23.halted, 1, 'budget 23 witnesses only the all-one path');
equal(at24.halted, 12, 'budget 24 witnesses paths with at most one zero');
equal(at34.halted, 2048, 'budget 34 witnesses every curated halt');
equal(at4096.halted, 2048, 'budget 4,096 retains all witnessed halts');
equal(at4096.errors, 0, 'complete curated fleet has no runtime errors');
equal(at4096.unresolved, 0, 'complete curated fleet has no unresolved members');
truth(at0.halted <= at23.halted && at23.halted <= at24.halted && at24.halted <= at34.halted, 'witnessed halt count is monotone in budget');
equal(at34.bound.n, 1n, 'fully halted fleet lower bound reduces to numerator one');
equal(at34.bound.d, 1n << BigInt(at34.wireBits - 11), '2,048 equal cylinders reduce by eleven powers of two');
equal(at34.byRound.reduce((a, b) => a + b, 0), 2048, 'per-round halt histogram sums to fleet size');

console.log('\nOPERABLE CERTIFICATE PERTURBATIONS');
const no84 = Array(12).fill(true); no84[11] = false;
const pageNo84 = page.certificate({ mask: no84, tailScale: 1, proofs: [true, true] });
truth(pageNo84.prefixLength < 64, 'withholding the length-84 row loses certified bits');
const wideTail = page.certificate({ mask: Array(12).fill(true), tailScale: 128, proofs: [true, true] });
truth(wideTail.prefixLength < 64, 'enlarging the residual tail loses certified bits');
const noProofA = page.certificate({ mask: Array(12).fill(true), tailScale: 1, proofs: [false, true] });
equal(noProofA.upper.n, 1n, 'removing first tail assumption sets conservative upper endpoint to one');
equal(noProofA.prefixLength, 0, 'removing first tail assumption certifies no leading bit');
const noProofB = page.certificate({ mask: Array(12).fill(true), tailScale: 1, proofs: [true, false] });
equal(noProofB.upper.n, 1n, 'removing second tail assumption sets conservative upper endpoint to one');
equal(noProofB.prefixLength, 0, 'removing second tail assumption certifies no leading bit');

console.log('\nMUTATION SWEEP');
const expectedFingerprint = `${independentKraft()}|${cert.tails.total.n}/${cert.tails.total.d}|${cert.common}|${cert.prefix}`;
function fingerprint(ls, hs, a, b, tailPow = 91, dataRatio = 63n, opcodeRatio = 81n) {
  const lower = fraction(independentKraft(ls, hs), 1n << 84n);
  const tails = independentTails(a, b, tailPow, dataRatio, opcodeRatio);
  const upper = plus(lower, tails.total);
  let common = 0;
  for (let bit = 1; bit <= 84; bit++) {
    if (floorAt(lower, bit) !== floorAt(upper, bit)) break;
    common = bit;
  }
  return `${independentKraft(ls, hs)}|${tails.total.n}/${tails.total.d}|${common}|${binaryAt(lower, common)}`;
}

const mutations = [
  ['first halt count +1', () => fingerprint(lengths, [2n, ...halts.slice(1)], noHaltPrefixes, withHaltPrefixes)],
  ['length-21 halt count +1', () => { const h = [...halts]; h[2]++; return fingerprint(lengths, h, noHaltPrefixes, withHaltPrefixes); }],
  ['length-84 halt count -1', () => { const h = [...halts]; h[11]--; return fingerprint(lengths, h, noHaltPrefixes, withHaltPrefixes); }],
  ['length 84 changed to 83', () => { const l = [...lengths]; l[11] = 83; return fingerprint(l, halts, noHaltPrefixes, withHaltPrefixes); }],
  ['HALT-free prefixes +1', () => fingerprint(lengths, halts, noHaltPrefixes + 1n, withHaltPrefixes)],
  ['HALT-containing prefixes -1', () => fingerprint(lengths, halts, noHaltPrefixes, withHaltPrefixes - 1n)],
  ['tail power 90', () => fingerprint(lengths, halts, noHaltPrefixes, withHaltPrefixes, 90)],
  ['tail power 92', () => fingerprint(lengths, halts, noHaltPrefixes, withHaltPrefixes, 92)],
  ['data geometric denominator 62', () => fingerprint(lengths, halts, noHaltPrefixes, withHaltPrefixes, 91, 62n, 81n)],
  ['opcode geometric denominator 80', () => fingerprint(lengths, halts, noHaltPrefixes, withHaltPrefixes, 91, 63n, 80n)],
  ['swap the two prefix counts', () => fingerprint(lengths, halts, withHaltPrefixes, noHaltPrefixes)],
  ['drop final row', () => fingerprint(lengths.slice(0, -1), halts.slice(0, -1), noHaltPrefixes, withHaltPrefixes)],
  ['off-by-one common-prefix loop', () => `${independentKraft()}|${cert.tails.total.n}/${cert.tails.total.d}|${cert.common + 1}|${binaryAt(cert.lower, cert.common + 1)}`],
  ['tail subtraction instead of addition', () => {
    const wrongUpper = fraction(cert.lower.n * cert.tails.total.d - cert.tails.total.n * cert.lower.d, cert.lower.d * cert.tails.total.d);
    let common = 0;
    for (let bit = 1; bit <= 84; bit++) {
      if (floorAt(cert.lower, bit) !== floorAt(wrongUpper, bit)) break;
      common = bit;
    }
    return `${independentKraft()}|${cert.tails.total.n}/${cert.tails.total.d}|${common}|${binaryAt(cert.lower, common)}`;
  }],
];
let caught = 0;
for (const [name, mutate] of mutations) {
  const detected = mutate() !== expectedFingerprint;
  if (detected) caught++;
  truth(detected, `mutation caught: ${name}`);
}

const parserMutations = [
  ['missing HALT', page.fleetCode().replace('%', '') + '00000000000'],
  ['double HALT', page.fleetCode() + '%00000000000'],
  ['nonbinary data', page.fleetCode() + '0000000000x'],
  ['unknown opcode', page.fleetCode().replace('!a', '~a') + '00000000000'],
];
for (const [name, source] of parserMutations) {
  let detected = false;
  try { page.compile(source); } catch { detected = true; }
  if (detected) caught++;
  truth(detected, `parser mutation caught: ${name}`);
}
const attempted = mutations.length + parserMutations.length;
console.log(`MUTATION RESULT  ${caught} caught / ${attempted} attempted`);
equal(caught, attempted, 'all deliberate mutations were caught');

console.log(`\nRESULT  ${checks - failures}/${checks} checks passed`);
if (failures) {
  console.error(`${failures} check${failures === 1 ? '' : 's'} failed`);
  process.exit(1);
}
console.log('All claims coupled, all mutations rejected.');
