import fs from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import zlib from 'node:zlib';

const root = path.resolve(import.meta.dirname, '../..');
const dataDir = path.join(import.meta.dirname, 'data');
const pagePath = path.join(root, 'public/strata/oeis-collision/index.html');
const entryPath = path.join(root, 'src/content/strata/oeis-collision.md');
let assertions = 0;

function ok(condition, message) {
  assertions += 1;
  if (!condition) throw new Error(`Assertion ${assertions} failed: ${message}`);
  console.log(`[${assertions}] PASS ${message}`);
}

function equal(actual, expected, message) {
  ok(actual === expected, `${message} (${String(actual)})`);
}

function publicationDateMatches(metadata, expected) {
  return metadata.datePublished === expected;
}

function cellMatches(actual, expected) {
  return actual.eligible === expected.eligible && actual.groups === expected.groups && actual.largest === expected.largest &&
    actual.total === expected.total && actual.diverged === expected.diverged && actual.duplicate === expected.duplicate &&
    actual.exact === expected.exact && actual.censored === expected.censored && actual.partition === expected.total;
}

function witnessMatches(witness) {
  const [a, b] = witness.terms;
  return lcp(a, b) === witness.shared && witness.mismatchPosition === witness.shared + 1 &&
    a.length >= witness.mismatchPosition && b.length >= witness.mismatchPosition;
}

function pairCount(size) {
  const n = BigInt(size);
  return n * (n - 1n) / 2n;
}

function vectorKey(terms, start, length = terms.length - start) {
  return terms.slice(start, start + length).join('\x1f');
}

function constantPrefix(terms, start, length) {
  for (let i = 1; i < length; i += 1) if (terms[start + i] !== terms[start]) return false;
  return true;
}

function parsePrimaryRows(gzipPath) {
  const text = zlib.gunzipSync(fs.readFileSync(gzipPath)).toString('utf8');
  const rows = [];
  for (const line of text.split('\n')) {
    const match = /^(A\d{6}) ,(.*),$/.exec(line);
    if (match) rows.push({ id: match[1], terms: match[2].split(',') });
  }
  return rows;
}

function parseNames(gzipPath) {
  const text = zlib.gunzipSync(fs.readFileSync(gzipPath)).toString('utf8');
  const duplicateOf = new Map();
  let rowCount = 0;
  for (const line of text.split('\n')) {
    const match = /^(A\d{6}) (.*)$/.exec(line);
    if (!match) continue;
    rowCount += 1;
    const duplicate = /^Duplicate of (A\d{6})\.$/.exec(match[2]);
    if (duplicate) duplicateOf.set(match[1], duplicate[1]);
  }
  return { rowCount, duplicateOf };
}

function visibleTieContributions(source, start, suppressConstant) {
  const vectors = new Map();
  for (const row of source) {
    if (row.terms.length <= start) continue;
    const terms = row.terms.slice(start);
    const key = terms.join('\x1f');
    vectors.set(key, (vectors.get(key) || 0) + 1);
  }
  const exact = Array(21).fill(0n);
  const censored = Array(21).fill(0n);
  for (const [key, count] of vectors) {
    const terms = key.split('\x1f');
    let constantThrough = 1;
    while (constantThrough < terms.length && terms[constantThrough] === terms[0]) constantThrough += 1;
    for (let k = 1; k <= Math.min(20, terms.length); k += 1) {
      if (!suppressConstant || k > constantThrough) exact[k] += pairCount(count);
    }
    let prefix = '';
    for (let length = 1; length < terms.length; length += 1) {
      prefix += (length === 1 ? '' : '\x1f') + terms[length - 1];
      const shorterCount = vectors.get(prefix);
      if (!shorterCount) continue;
      const contribution = BigInt(count) * BigInt(shorterCount);
      for (let k = 1; k <= Math.min(20, length); k += 1) {
        if (!suppressConstant || k > constantThrough) censored[k] += contribution;
      }
    }
  }
  return { exact, censored };
}

function classifiedDuplicatePairs(duplicateOf, byId, included, start) {
  const seen = new Set();
  const pairs = [];
  for (const [id, target] of duplicateOf) {
    if (!included.has(id) || !included.has(target)) continue;
    const unordered = [id, target].sort().join(':');
    if (seen.has(unordered)) continue;
    seen.add(unordered);
    const a = byId.get(id)?.terms.slice(start);
    const b = byId.get(target)?.terms.slice(start);
    if (!a || !b) continue;
    const shared = Math.min(a.length, b.length);
    let lcp = 0;
    while (lcp < shared && a[lcp] === b[lcp]) lcp += 1;
    let kind = 'diverged';
    if (lcp === shared) kind = a.length === b.length ? 'exact' : 'censored';
    let constantThrough = 1;
    while (constantThrough < lcp && a[constantThrough] === a[0]) constantThrough += 1;
    pairs.push({ ids: [id, target], lcp, kind, constantThrough });
  }
  return pairs;
}

function parentStats(source, start, k, suppressConstant) {
  const groups = new Map();
  for (const row of source) {
    if (row.terms.length < start + k) continue;
    if (suppressConstant && constantPrefix(row.terms, start, k)) continue;
    const key = vectorKey(row.terms, start, k);
    const counts = groups.get(key) || [0, 0, 0];
    counts[0] += 1;
    if (row.terms.length >= start + k + 1) counts[1] += 1;
    if (row.terms.length >= start + k + 5) counts[2] += 1;
    groups.set(key, counts);
  }
  let eligible = 0, collisionGroups = 0, largest = 0;
  const pairs = [0n, 0n, 0n];
  for (const counts of groups.values()) {
    eligible += counts[0];
    largest = Math.max(largest, counts[0]);
    if (counts[0] > 1) collisionGroups += 1;
    for (let i = 0; i < 3; i += 1) pairs[i] += pairCount(counts[i]);
  }
  return { eligible, collisionGroups, largest, total: pairs[0], hazardDen: { 1: pairs[1], 5: pairs[2] } };
}

function childStats(source, start, k, suppressConstant) {
  const children = new Map();
  for (const row of source) {
    if (row.terms.length < start + k + 1) continue;
    if (suppressConstant && constantPrefix(row.terms, start, k)) continue;
    const key = vectorKey(row.terms, start, k + 1);
    const counts = children.get(key) || [0, 0];
    counts[0] += 1;
    if (row.terms.length >= start + k + 5) counts[1] += 1;
    children.set(key, counts);
  }
  const same = { 1: 0n, 5: 0n };
  for (const counts of children.values()) {
    same[1] += pairCount(counts[0]);
    same[5] += pairCount(counts[1]);
  }
  return same;
}

function primaryScenario(allRows, duplicateOf, byId, options) {
  const source = options.removeDuplicates ? allRows.filter((row) => !duplicateOf.has(row.id)) : allRows;
  const included = new Set(source.map((row) => row.id));
  const ties = visibleTieContributions(source, options.start, options.suppressConstant);
  const markedPairs = classifiedDuplicatePairs(duplicateOf, byId, included, options.start);
  const cells = [];
  for (let k = 1; k <= 20; k += 1) {
    const parent = parentStats(source, options.start, k, options.suppressConstant);
    const same = childStats(source, options.start, k, options.suppressConstant);
    const marked = { total: 0n, diverged: 0n, exact: 0n, censored: 0n };
    for (const pair of markedPairs) {
      if (pair.lcp >= k && (!options.suppressConstant || k > pair.constantThrough)) {
        marked.total += 1n;
        marked[pair.kind] += 1n;
      }
    }
    const cell = {
      k,
      eligible: parent.eligible,
      groups: parent.collisionGroups,
      largest: parent.largest,
      total: parent.total,
      duplicate: marked.total,
      exact: ties.exact[k] - marked.exact,
      censored: ties.censored[k] - marked.censored,
      diverged: parent.total - ties.exact[k] - ties.censored[k] - marked.diverged,
      hazard: {}
    };
    for (const extra of [1, 5]) {
      const den = parent.hazardDen[extra];
      cell.hazard[extra] = { den, same: same[extra], split: den - same[extra] };
    }
    cells.push(cell);
  }
  return { cells, markedPairs, sourceCount: source.length };
}

function lcp(a, b) {
  const shared = Math.min(a.length, b.length);
  let count = 0;
  while (count < shared && a[count] === b[count]) count += 1;
  return count;
}

const page = fs.readFileSync(pagePath, 'utf8');
const dataText = fs.readFileSync(path.join(dataDir, 'audit-record.json'), 'utf8');
const islandMatch = /<script id="oeis-audit-data" type="application\/json">([\s\S]*?)<\/script>/.exec(page);
ok(Boolean(islandMatch), 'page contains the audit data island');
equal(islandMatch[1], dataText, 'page data island equals the committed distilled record byte for byte');
const audit = JSON.parse(dataText);

const engineMatch = /<script id="oeis-engine">([\s\S]*?)<\/script>/.exec(page);
ok(Boolean(engineMatch), 'page engine was extracted');
const context = { globalThis: {} };
vm.runInNewContext(engineMatch[1], context, { filename: 'oeis-page-engine.js' });
const pageEngine = context.globalThis.OEISCollisionEngine;
ok(Boolean(pageEngine), 'shipped page engine executed');

const markdown = fs.readFileSync(entryPath, 'utf8');
const dateMatch = /^date:\s*([^\s]+)$/m.exec(markdown);
ok(Boolean(dateMatch), 'publication date was read from markdown frontmatter');
const jsonLdMatch = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(page);
ok(Boolean(jsonLdMatch), 'JSON-LD block was extracted');
const jsonLd = JSON.parse(jsonLdMatch[1]);
ok(publicationDateMatches(jsonLd, dateMatch[1]), 'JSON-LD publication date matches markdown');
const correctionDates = [...markdown.matchAll(/^\*(?:Corrected|Updated) (\d{4}-\d{2}-\d{2}):\*/gm)].map((match) => match[1]);
const modifiedDate = [dateMatch[1], ...correctionDates].sort().at(-1);
equal(jsonLd.dateModified, modifiedDate, 'JSON-LD modification date matches the latest publication, correction or update date');

console.log('Loading and independently parsing the official bulk snapshots.');
const rows = parsePrimaryRows(path.join(dataDir, 'stripped.gz'));
const names = parseNames(path.join(dataDir, 'names.gz'));
const byId = new Map(rows.map((row) => [row.id, row]));
equal(rows.length, pageEngine.cell(audit, 'literalAll', 1).eligible, 'primary sequence-row count reaches the page through the group ledger');
equal(names.rowCount, audit.names, 'primary name-row count matches snapshot metadata');
equal(names.duplicateOf.size, audit.variants.literalAll.markedPairs.length, 'exact duplicate-name parser count matches the ledger');

const anchorA = byId.get('A004258');
const anchorB = byId.get('A029837');
ok(Boolean(anchorA && anchorB), 'both anchor A-numbers exist in the primary sequence rows');
const independentAnchorLcp = lcp(anchorA.terms, anchorB.terms);
equal(independentAnchorLcp, anchorA.terms.length, 'independent anchor comparison agrees through every A004258 term');
equal(anchorA.terms.length, anchorB.terms.length, 'anchor vectors have equal visible length');
const anchorText = fs.readFileSync(path.join(dataDir, 'A004258.txt'), 'utf8');
ok(/^%N A004258 Duplicate of A029837\.$/m.test(anchorText), 'official anchor text names A029837 as the duplicate target');
ok(/^%K A004258 dead$/m.test(anchorText), 'official anchor text carries keyword dead');
const shippedAnchor = pageEngine.anchor(audit);
equal(shippedAnchor.compared, independentAnchorLcp, 'page engine reproduces the independently counted anchor length');
equal(shippedAnchor.mismatchCount, 0, 'page engine reproduces zero anchor mismatches');

for (let k = 1; k <= 20; k += 1) {
  const witness = audit.witnesses[k - 1];
  const a = byId.get(witness.ids[0])?.terms;
  const b = byId.get(witness.ids[1])?.terms;
  ok(Boolean(a && b), `k=${k} witness A-numbers exist`);
  equal(lcp(a, b), witness.shared, `k=${k} witness shared-prefix length is reproduced`);
  equal(witness.mismatchPosition, witness.shared + 1, `k=${k} witness mismatch position follows the shared prefix`);
  ok(witnessMatches(witness), `k=${k} displayed witness terms reproduce the shared prefix and later mismatch`);
}

const scenarios = [
  ['literalAll', { start: 0, removeDuplicates: false, suppressConstant: false }],
  ['literalCanonical', { start: 0, removeDuplicates: true, suppressConstant: false }],
  ['literalAllNoConstant', { start: 0, removeDuplicates: false, suppressConstant: true }],
  ['literalCanonicalNoConstant', { start: 0, removeDuplicates: true, suppressConstant: true }],
  ['dropFirstAll', { start: 1, removeDuplicates: false, suppressConstant: false }],
  ['dropFirstCanonical', { start: 1, removeDuplicates: true, suppressConstant: false }],
  ['dropFirstAllNoConstant', { start: 1, removeDuplicates: false, suppressConstant: true }],
  ['dropFirstCanonicalNoConstant', { start: 1, removeDuplicates: true, suppressConstant: true }]
];
const primary = new Map();
for (const [key, options] of scenarios) {
  console.log(`Independently recomputing scenario ${key}.`);
  const result = primaryScenario(rows, names.duplicateOf, byId, options);
  primary.set(key, result);
  equal(result.markedPairs.length, audit.variants[key].markedPairs.length, `${key} duplicate-link count`);
  for (const expected of result.cells) {
    const actual = pageEngine.cell(audit, key, expected.k);
    ok(cellMatches(actual, expected), `${key} k=${expected.k} recomputes eligible, groups, largest group, total, and all four disjoint outcomes`);
    for (const extra of [1, 5]) {
      const hazard = pageEngine.hazard(audit, key, expected.k, extra);
      const wanted = expected.hazard[extra];
      ok(hazard.den === wanted.den && hazard.same === wanted.same && hazard.split === wanted.split,
        `${key} k=${expected.k} k+${extra} visibility hazard recomputes denominator, survivors, and splits`);
    }
  }
}

const baseline = primary.get('literalAll').cells[5];
ok(cellMatches(pageEngine.cell(audit, 'literalAll', 6), baseline), 'CONTROL true pair coefficient stays GREEN');
ok(witnessMatches(audit.witnesses[5]), 'CONTROL true witness mismatch stays GREEN');
ok(publicationDateMatches(jsonLd, dateMatch[1]), 'CONTROL true publication date stays GREEN');
console.log('Running deliberate corruptions. Each must disagree with the independently recomputed result.');
const badAnchor = structuredClone(audit);
badAnchor.anchor.b.terms[0] = String(BigInt(badAnchor.anchor.b.terms[0]) + 1n);
ok(!pageEngine.anchor(badAnchor).equal, 'MUTATION anchor term corruption goes RED');

const badGroup = structuredClone(audit);
badGroup.variants.literalAll.cells[5].ledger.prefixRuns[1][1] += 1;
ok(pageEngine.cell(badGroup, 'literalAll', 6).total !== baseline.total, 'MUTATION prefix-group multiplicity corruption goes RED');

const badCoefficientContext = { globalThis: {} };
vm.runInNewContext(engineMatch[1].replace('n*(n-1n)/2n', 'n*(n+1n)/2n'), badCoefficientContext);
ok(!cellMatches(badCoefficientContext.globalThis.OEISCollisionEngine.cell(audit, 'literalAll', 6), baseline),
  'MUTATION n(n+1)/2 pair coefficient goes RED');

const badDuplicate = structuredClone(audit);
badDuplicate.variants.literalAll.markedPairs.pop();
ok(pageEngine.cell(badDuplicate, 'literalAll', 6).duplicate !== baseline.duplicate, 'MUTATION duplicate-link deletion goes RED');

const badExact = structuredClone(audit);
badExact.variants.literalAll.cells[5].ledger.exactRuns.push(['2', 1]);
ok(pageEngine.cell(badExact, 'literalAll', 6).exact !== baseline.exact, 'MUTATION exact-vector multiplicity corruption goes RED');

const badCensor = structuredClone(audit);
badCensor.variants.literalAll.cells[5].ledger.censoredRuns.push(['1', 1]);
ok(pageEngine.cell(badCensor, 'literalAll', 6).censored !== baseline.censored, 'MUTATION censoring contribution corruption goes RED');

const badHazard = structuredClone(audit);
badHazard.variants.literalAll.cells[5].ledger.nextPrefixRuns['1'].push(['2', 1]);
ok(pageEngine.hazard(badHazard, 'literalAll', 6, 1).split !== baseline.hazard[1].split, 'MUTATION next-term survivor corruption goes RED');

const badWitness = structuredClone(audit);
badWitness.witnesses[5].terms[1][badWitness.witnesses[5].shared] = badWitness.witnesses[5].terms[0][badWitness.witnesses[5].shared];
ok(!witnessMatches(badWitness.witnesses[5]), 'MUTATION witness mismatch corruption goes RED');

const badDate = { ...jsonLd, datePublished: '2026-08-02' };
ok(!publicationDateMatches(badDate, dateMatch[1]), 'MUTATION publication-date corruption goes RED');

console.log(`All ${assertions} assertions passed.`);
