#!/usr/bin/env node

import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
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', 'half-the-cube-plus-one', 'index.html');
const html = fs.readFileSync(pagePath, 'utf8');
const match = html.match(/<script id="instrument-code">([\s\S]*?)<\/script>/);

let failures = 0;
let assertions = 0;

function report(condition, message) {
  assertions += 1;
  if (condition) {
    console.log(`PASS ${message}`);
  } else {
    failures += 1;
    console.error(`FAIL ${message}`);
  }
}

report(Boolean(match), 'the shipped instrument script is extractable');
if (!match) process.exit(1);

function loadLab(source) {
  const context = { console, Map, Math, Number, Array, Object, String, Boolean, Infinity };
  vm.createContext(context);
  vm.runInContext(source, context, { filename:'shipped-instrument.js' });
  return context.CubeLab;
}

const lab = loadLab(match[1]);
report(Boolean(lab && lab.buildSignedMatrix && lab.booleanStats), 'the extracted shipped API loads');

function refPopcount(value) {
  return value.toString(2).split('').filter(bit => bit === '1').length;
}

function refHamming(a, b) {
  return refPopcount(a ^ b);
}

function refSignedMatrix(n) {
  const size = 2 ** n;
  return Array.from({ length:size }, (_, row) =>
    Array.from({ length:size }, (_, column) => {
      const difference = row ^ column;
      if (!difference || (difference & (difference - 1))) return 0;
      const bit = Math.log2(difference);
      let higherOnes = 0;
      for (let k = bit + 1; k < n; k += 1) {
        if (row & (2 ** k)) higherOnes += 1;
      }
      return higherOnes % 2 ? -1 : 1;
    })
  );
}

function sameMatrix(left, right) {
  return left.length === right.length && left.every((row, r) =>
    row.length === right[r].length && row.every((value, c) => value === right[r][c])
  );
}

function refInduced(n, selected) {
  const size = 2 ** n;
  const degrees = Array(size).fill(0);
  const radius = Array(size).fill(0);
  const ids = [];
  for (let v = 0; v < size; v += 1) {
    if (!selected[v]) continue;
    ids.push(v);
    for (let u = 0; u < size; u += 1) {
      if (!selected[u] || u === v) continue;
      const distance = refHamming(u, v);
      if (distance === 1) degrees[v] += 1;
      if (distance === 1 || distance === 2) radius[v] += 1;
    }
  }
  const maxDegree = ids.reduce((best, id) => Math.max(best, degrees[id]), 0);
  const best = parity => ids
    .filter(id => refPopcount(id) % 2 === parity)
    .sort((a, b) => radius[b] - radius[a] || a - b)[0] ?? null;
  return { ids, degrees, radius, maxDegree, even:best(0), odd:best(1) };
}

function selectedFromMask(size, mask) {
  return Array.from({ length:size }, (_, id) => Boolean(mask & (2 ** id)));
}

for (let n = 1; n <= 6; n += 1) {
  report(
    sameMatrix(lab.buildSignedMatrix(n), refSignedMatrix(n)),
    `A_${n} matches the independent direct edge-sign formula`
  );
}

let certificateMismatch = null;
for (let n = 1; n <= 6; n += 1) {
  const matrix = lab.buildSignedMatrix(n);
  const rootN = Math.sqrt(n);
  const spectrum = lab.jacobiEigen(matrix).values;
  const positive = spectrum.filter(value => Math.abs(value - rootN) < 1e-7).length;
  const negative = spectrum.filter(value => Math.abs(value + rootN) < 1e-7).length;
  if (matrix.length !== 2 ** n ||
      lab.threshold(n) !== 2 ** (n - 1) + 1 ||
      lab.matrixSquareError(matrix, n) !== 0 ||
      positive !== 2 ** (n - 1) ||
      negative !== 2 ** (n - 1)) {
    certificateMismatch = n;
    break;
  }
}
report(
  !certificateMismatch,
  'published dimensions, half-plus-one thresholds, square identities, and spectral multiplicities hold for n=1 through 6'
);

let subsetMismatch = null;
for (let n = 2; n <= 4 && !subsetMismatch; n += 1) {
  const size = 2 ** n;
  for (let mask = 0; mask < 2 ** size; mask += 1) {
    const selected = selectedFromMask(size, mask);
    const got = lab.inducedStats(n, selected);
    const want = refInduced(n, selected);
    const degreeEqual = got.degrees.every((value, id) => value === want.degrees[id]);
    const radiusEqual = got.radius.every((value, id) => value === want.radius[id]);
    if (!degreeEqual || !radiusEqual || got.maxDegree !== want.maxDegree ||
        got.radiusEven !== want.even || got.radiusOdd !== want.odd) {
      subsetMismatch = { n, mask };
      break;
    }
  }
}
report(!subsetMismatch, 'every reachable cube selection for n=2,3,4 matches independent degree and radius counts');

let theoremFailure = null;
for (let n = 2; n <= 4 && !theoremFailure; n += 1) {
  const size = 2 ** n;
  for (let mask = 0; mask < 2 ** size; mask += 1) {
    const count = refPopcount(mask);
    if (count <= size / 2) continue;
    const stats = lab.inducedStats(n, selectedFromMask(size, mask));
    if (stats.maxDegree < Math.ceil(Math.sqrt(n)) ||
        stats.radiusEven === null || stats.radiusOdd === null ||
        stats.radius[stats.radiusEven] < n || stats.radius[stats.radiusOdd] < n) {
      theoremFailure = { n, mask };
      break;
    }
  }
}
report(!theoremFailure, 'all theorem-eligible selections for n=2,3,4 satisfy both published guarantees');

let deterministicState = 0x6d2b79f5;
function randomBit() {
  deterministicState ^= deterministicState << 13;
  deterministicState ^= deterministicState >>> 17;
  deterministicState ^= deterministicState << 5;
  return deterministicState >>> 0;
}

let largeMismatch = null;
for (const n of [5, 6]) {
  const size = 2 ** n;
  const corpus = [];
  corpus.push(Array.from({ length:size }, (_, id) => refPopcount(id) % 2 === 0));
  corpus.push(Array.from({ length:size }, (_, id) => refPopcount(id) % 2 === 0 || id === 1));
  corpus.push(Array(size).fill(true));
  for (let sample = 0; sample < 80; sample += 1) {
    let selected = Array.from({ length:size }, () => (randomBit() & 3) !== 0);
    while (selected.filter(Boolean).length <= size / 2) {
      selected[randomBit() % size] = true;
    }
    corpus.push(selected);
  }
  for (const selected of corpus) {
    const got = lab.inducedStats(n, selected);
    const want = refInduced(n, selected);
    if (got.maxDegree !== want.maxDegree ||
        got.degrees.some((value, id) => value !== want.degrees[id]) ||
        got.radius.some((value, id) => value !== want.radius[id])) {
      largeMismatch = n;
      break;
    }
  }
}
report(!largeMismatch, 'all shipped presets and deterministic n=5,6 cube selections match the independent reference');

function refMobius(values, n) {
  return values.map((_, mask) => {
    let coefficient = 0;
    for (let subset = mask; ; subset = (subset - 1) & mask) {
      const sign = (refPopcount(mask) - refPopcount(subset)) % 2 ? -1 : 1;
      coefficient += sign * values[subset];
      if (subset === 0) break;
    }
    return coefficient;
  });
}

function refBooleanStats(values, n) {
  const size = 2 ** n;
  const local = values.map((value, input) => {
    let count = 0;
    for (let bit = 0; bit < n; bit += 1) {
      if (value !== values[input ^ (2 ** bit)]) count += 1;
    }
    return count;
  });
  const ofValue = bit => local.filter((_, input) => values[input] === bit);
  const s0 = ofValue(0).reduce((best, value) => Math.max(best, value), 0);
  const s1 = ofValue(1).reduce((best, value) => Math.max(best, value), 0);
  const coefficients = refMobius(values, n);
  const degree = coefficients.reduce(
    (best, value, mask) => value ? Math.max(best, refPopcount(mask)) : best,
    0
  );
  return { local, s0, s1, coefficients, degree };
}

let truthMismatch = null;
let degreeBoundMismatch = null;
for (let n = 2; n <= 3 && !truthMismatch; n += 1) {
  const rows = 2 ** n;
  for (let table = 0; table < 2 ** rows; table += 1) {
    const values = Array.from({ length:rows }, (_, row) => (table >>> row) & 1);
    const got = lab.booleanStats(values, n);
    const want = refBooleanStats(values, n);
    if (got.s0 !== want.s0 || got.s1 !== want.s1 || got.degree !== want.degree ||
        got.local.some((value, input) => value !== want.local[input]) ||
        got.coefficients.some((value, mask) => value !== want.coefficients[mask])) {
      truthMismatch = { n, table };
      break;
    }
    if (got.degree > got.s0 * got.s1 ||
        got.bs > Math.max(got.s0, got.s1) ** 4) {
      degreeBoundMismatch = { n, table };
      break;
    }
  }
}
report(!truthMismatch, 'every Boolean function for n=2,3 matches independent sensitivity and inclusion-exclusion degree');
report(
  !degreeBoundMismatch,
  'every Boolean function for n=2,3 satisfies both displayed published complexity bounds'
);

function refBlockSensitivity(values, n, input) {
  const sensitive = [];
  for (let block = 1; block < 2 ** n; block += 1) {
    if (values[input] !== values[input ^ block]) sensitive.push(block);
  }
  function pack(remaining, used) {
    let best = 0;
    remaining.forEach((block, index) => {
      if ((block & used) === 0) {
        best = Math.max(best, 1 + pack(remaining.slice(index + 1), used | block));
      }
    });
    return best;
  }
  return pack(sensitive, 0);
}

let blockMismatch = null;
for (let n = 2; n <= 4 && !blockMismatch; n += 1) {
  const rows = 2 ** n;
  for (let sample = 0; sample < 64; sample += 1) {
    const values = Array.from({ length:rows }, () => randomBit() & 1);
    for (let input = 0; input < rows; input += 1) {
      if (lab.blockSensitivityAt(values, n, input) !== refBlockSensitivity(values, n, input)) {
        blockMismatch = { n, sample, input };
        break;
      }
    }
  }
}
report(!blockMismatch, 'exhaustive disjoint-block packing matches an independent recursive reference');

function matVec(matrix, vector) {
  return matrix.map(row => row.reduce((sum, value, i) => sum + value * vector[i], 0));
}

function norm(vector) {
  return Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0));
}

function shiftedPowerLargest(matrix, shift) {
  if (!matrix.length) return 0;
  let vector = Array.from({ length:matrix.length }, (_, i) => i === 0 ? 1 : 1 / (i + 2));
  let length = norm(vector);
  vector = vector.map(value => value / length);
  for (let iteration = 0; iteration < 1200; iteration += 1) {
    let next = matVec(matrix, vector).map((value, i) => value + shift * vector[i]);
    length = norm(next);
    if (!length) return -shift;
    vector = next.map(value => value / length);
  }
  const av = matVec(matrix, vector);
  return vector.reduce((sum, value, i) => sum + value * av[i], 0);
}

let eigenMismatch = null;
for (const n of [2, 3, 4, 5, 6]) {
  const size = 2 ** n;
  const presets = [
    Array.from({ length:size }, (_, id) => refPopcount(id) % 2 === 0 || id === 1),
    Array(size).fill(true)
  ];
  for (const selected of presets) {
    const ids = selected.map((on, id) => on ? id : -1).filter(id => id >= 0);
    const principal = lab.principalMatrix(lab.buildSignedMatrix(n), ids);
    const pageValue = lab.largestEigenpair(principal);
    const referenceValue = shiftedPowerLargest(principal, n + 1);
    if (Math.abs(pageValue.value - referenceValue) > 2e-7 || pageValue.residual > 2e-7) {
      eigenMismatch = { n, page:pageValue.value, reference:referenceValue, residual:pageValue.residual };
      break;
    }
  }
}
report(!eigenMismatch, 'Jacobi eigenvalue estimates match independent shifted power iteration on every shipped spectral preset');

const requiredSourceText = [
  'DOI:10.4007/annals.2019.190.3.6',
  'arXiv:1907.00847',
  '949-955',
  '28 October 2019',
  'DOI:10.4230/LIPIcs.MFCS.2020.62',
  '18 August 2020',
  'DOI:10.1145/3777401',
  '24 February 2026',
  'DOI:10.1016/j.tcs.2022.12.037',
  '10 February 2023'
];
report(
  requiredSourceText.every(text => html.includes(text)),
  'all source-checked identifiers, page range, and publication dates are visible'
);

report(
  html.includes('distance exactly one or exactly two') && html.includes('It excludes v itself'),
  'the shipped radius convention excludes the center exactly as the source notation does'
);
report(
  html.includes('optimal universal relation between block sensitivity and sensitivity remains unresolved'),
  'the time-sensitive open statement is present and narrowly worded'
);
report(
  !html.includes(String.fromCodePoint(0x2014)),
  'the shipped page contains no em dash'
);

const mutationNeedle = 'return Math.pow(2, n);';
const mutatedSource = match[1].replace(mutationNeedle, 'return Math.pow(2, n) + 1;');
let mutationDetected = false;
if (mutatedSource !== match[1]) {
  const mutated = loadLab(mutatedSource);
  mutationDetected = mutated.cubeSize(6) !== 64;
}
report(mutationDetected, 'deliberate cubeSize mutation was detected by the differential anchor');

console.log(`${failures ? 'FAIL' : 'PASS'} ${assertions - failures}/${assertions} assertions`);
process.exit(failures ? 1 : 0);
