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

const root = path.resolve(import.meta.dirname, '../..');
const researchDir = path.join(root, 'research/sequence-extension');
const dataDir = path.join(researchDir, 'data');
const htmlPath = path.join(root, 'public/strata/sequence-extension/index.html');
const markdownPath = path.join(root, 'src/content/strata/sequence-extension.md');
let assertions = 0;

function check(condition, label) {
  assertions += 1;
  if (!condition) throw new Error(`assertion ${assertions} failed: ${label}`);
  console.log(`ok ${assertions} - ${label}`);
}

function parseBFile(text) {
  return text.split(/\r?\n/)
    .map((line) => line.trim())
    .filter((line) => line && !line.startsWith('#'))
    .map((line) => {
      const [n, value] = line.split(/\s+/).map(Number);
      return { n, value };
    });
}

function integerPartitions(n) {
  const result = [];
  const current = [];
  function descend(left, minimum) {
    if (left === 0) {
      result.push([...current]);
      return;
    }
    for (let part = minimum; part <= left; part += 1) {
      current.push(part);
      descend(left - part, part);
      current.pop();
    }
  }
  descend(n, 1);
  return result;
}

function edgeConnected(masks) {
  if (masks.length === 0) return true;
  const reached = new Set([0]);
  for (let changed = true; changed;) {
    changed = false;
    for (let i = 0; i < masks.length; i += 1) {
      if (reached.has(i)) continue;
      for (const j of reached) {
        if (masks[i] & masks[j]) {
          reached.add(i);
          changed = true;
          break;
        }
      }
    }
  }
  return reached.size === masks.length;
}

function independentCertificate(masks, vertexCount) {
  const order = masks.map((_, i) => i);
  let best;
  function visit(k) {
    if (k === order.length) {
      const columns = [];
      for (let vertex = 0; vertex < vertexCount; vertex += 1) {
        let column = '';
        for (const edgeIndex of order) column += masks[edgeIndex] & (1 << vertex) ? '1' : '0';
        columns.push(column);
      }
      const key = columns.sort().join('|');
      if (best === undefined || key < best) best = key;
      return;
    }
    for (let i = k; i < order.length; i += 1) {
      [order[k], order[i]] = [order[i], order[k]];
      visit(k + 1);
      [order[k], order[i]] = [order[i], order[k]];
    }
  }
  visit(0);
  return best;
}

function independentCount(weight) {
  if (weight === 0) return { value: 1, tested: 1, valid: 1 };
  const classes = new Set();
  let tested = 0;
  let valid = 0;
  for (const shape of integerPartitions(weight)) {
    const labels = new Array(weight).fill(0);
    function consume() {
      tested += 1;
      const masks = [];
      let position = 0;
      let highest = 0;
      for (const size of shape) {
        let mask = 0;
        for (let j = 0; j < size; j += 1) {
          const label = labels[position];
          position += 1;
          const bit = 1 << label;
          if (mask & bit) return;
          mask |= bit;
          highest = Math.max(highest, label);
        }
        masks.push(mask);
      }
      for (let i = 0; i < masks.length; i += 1) {
        for (let j = i + 1; j < masks.length; j += 1) {
          if ((masks[i] & ~masks[j]) === 0 || (masks[j] & ~masks[i]) === 0) return;
        }
      }
      if (!edgeConnected(masks)) return;
      valid += 1;
      classes.add(independentCertificate(masks, highest + 1));
    }
    function assign(position, highest) {
      if (position === weight) {
        consume();
        return;
      }
      for (let label = 0; label <= highest + 1; label += 1) {
        labels[position] = label;
        assign(position + 1, Math.max(highest, label));
      }
    }
    assign(1, 0);
  }
  return { value: classes.size, tested, valid };
}

function independentInspect(edges, expectedWeight) {
  const names = [...new Set(edges.flat())];
  const index = new Map(names.map((name, i) => [name, i]));
  const masks = edges.map((edge) => edge.reduce((mask, vertex) => mask | (1 << index.get(vertex)), 0));
  const nonemptyAndSimple = edges.every((edge) => edge.length > 0 && new Set(edge).size === edge.length);
  const antichain = nonemptyAndSimple && masks.every((a, i) => masks.every((b, j) => i === j || (a & ~b) !== 0));
  return {
    valid: antichain && edgeConnected(masks) && edges.flat().length === expectedWeight,
    certificate: independentCertificate(masks, names.length),
    profile: edges.map((edge) => edge.length).sort((a, b) => a - b).join(','),
  };
}

function independentEuler(connected, maximum) {
  const all = new Array(maximum + 1).fill(0);
  all[0] = 1;
  for (let n = 1; n <= maximum; n += 1) {
    let numerator = 0;
    for (let j = 1; j <= n; j += 1) {
      let divisorSum = 0;
      for (let divisor = 1; divisor <= j; divisor += 1) {
        if (j % divisor === 0) divisorSum += divisor * (connected[divisor] || 0);
      }
      numerator += divisorSum * all[n - j];
    }
    check(numerator % n === 0, `Euler coefficient at weight ${n} is integral`);
    all[n] = numerator / n;
  }
  return all;
}

const html = fs.readFileSync(htmlPath, 'utf8');
const markdown = fs.readFileSync(markdownPath, 'utf8');
const a293607Text = fs.readFileSync(path.join(dataDir, 'A293607-b.txt'), 'utf8');
const a293606Text = fs.readFileSync(path.join(dataDir, 'A293606-b.txt'), 'utf8');
const a293607Json = JSON.parse(fs.readFileSync(path.join(dataDir, 'A293607.json'), 'utf8'))[0];
const a293606Json = JSON.parse(fs.readFileSync(path.join(dataDir, 'A293606.json'), 'utf8'))[0];
const auditData = JSON.parse(fs.readFileSync(path.join(dataDir, 'weight-10-representatives.json'), 'utf8'));
const publishedConnected = parseBFile(a293607Text);
const publishedAll = parseBFile(a293606Text);

check(a293607Json.number === 293607, 'primary JSON record identifies A293607');
check(a293607Json.name === 'Number of unlabeled clutters of weight n.', 'primary JSON record has the checked A293607 title');
check(a293607Json.author === '_Gus Wiseman_, Oct 13 2017', 'primary JSON record has the checked author field');
check(a293607Json.revision === 7, 'primary JSON record has revision 7');
check(a293607Json.data.split(',').map(Number).join(',') === publishedConnected.map((row) => row.value).join(','), 'A293607 JSON and b-file agree field for field on values');
check(a293606Json.number === 293606 && a293606Json.formula.includes('Euler transform of A293607.'), 'primary A293606 record names the Euler transform relation');
check(a293606Json.data.split(',').map(Number).join(',') === publishedAll.map((row) => row.value).join(','), 'A293606 JSON and b-file agree on published values');

const embeddedConnected = html.match(/<script type="text\/plain" id="a293607-b">([\s\S]*?)<\/script>/)?.[1];
const embeddedAll = html.match(/<script type="text\/plain" id="a293606-b">([\s\S]*?)<\/script>/)?.[1];
const embeddedAuditText = html.match(/<script type="application\/json" id="weight10-data">([\s\S]*?)<\/script>/)?.[1];
check(embeddedConnected?.trim() === a293607Text.trim(), 'browser A293607 data island matches the committed primary record');
check(embeddedAll?.trim() === a293606Text.trim(), 'browser A293606 data island matches the committed primary record');
check(embeddedAuditText === fs.readFileSync(path.join(dataDir, 'weight-10-representatives.json'), 'utf8').trim(), 'browser audit island matches the committed representative bytes');

console.log('# independent enumeration from the finite definition');
const independent = [];
for (let weight = 0; weight <= 10; weight += 1) {
  const start = performance.now();
  const result = independentCount(weight);
  independent.push(result);
  console.log(`# weight ${weight}: ${result.value}, tested ${result.tested}, valid ${result.valid}, ${(performance.now() - start).toFixed(1)} ms`);
  if (weight <= 9) check(result.value === publishedConnected[weight].value, `independent enumerator reproduces A293607(${weight})`);
}
check(independent[10].value === auditData.representatives.length, 'independent full enumeration agrees with the weight-10 representative count');

const independentProfiles = new Map();
const independentCards = new Set();
auditData.representatives.forEach((edges, index) => {
  const inspected = independentInspect(edges, auditData.weight);
  check(inspected.valid, `representative ${index + 1} is a connected antichain of the stated weight`);
  check(inspected.certificate === auditData.canonicalCertificates[index], `representative ${index + 1} regenerates its canonical card`);
  independentCards.add(inspected.certificate);
  independentProfiles.set(inspected.profile, (independentProfiles.get(inspected.profile) || 0) + 1);
});
check(independentCards.size === auditData.representatives.length, 'all independently regenerated canonical cards are distinct');
check(JSON.stringify(Object.fromEntries([...independentProfiles].sort())) === JSON.stringify(auditData.profiles), 'independent edge-size profile table matches the shipped table');

const connectedThroughTen = independent.map((result) => result.value);
const transformed = independentEuler(connectedThroughTen, 10);
for (const row of publishedAll) check(transformed[row.n] === row.value, `Euler transform reproduces A293606(${row.n})`);

const engineSource = html.match(/<script id="sequence-engine">([\s\S]*?)<\/script>/)?.[1];
check(Boolean(engineSource), 'shipped page engine is present');
const context = { globalThis: {}, Map, Set };
vm.runInNewContext(engineSource, context, { filename: 'sequence-extension-page-engine.js' });
const pageEngine = context.globalThis.SequenceExtensionEngine;
check(Boolean(pageEngine), 'shipped page engine executes');
const pageAnchor = pageEngine.enumerateWeights(9);
check(pageAnchor.map((row) => row.value).join(',') === publishedConnected.map((row) => row.value).join(','), 'shipped page engine independently reproduces the complete anchor');
const pageAudit = pageEngine.validateAudit(JSON.parse(embeddedAuditText));
check(pageAudit.valid && pageAudit.sum === independent[10].value, 'shipped page audit agrees with the independent weight-10 enumeration');
check(JSON.stringify(pageAudit.profiles) === JSON.stringify(auditData.profiles), 'shipped page engine regenerates every profile count');
check(pageEngine.eulerTransform(connectedThroughTen, 10).join(',') === transformed.join(','), 'shipped page Euler transform agrees with the independent transform');
check(pageEngine.candidateCount(10) === independent[10].tested, 'shipped page derives the full weight-10 candidate count');

const frontmatterDate = markdown.match(/^date:\s*(\S+)$/m)?.[1];
const jsonLd = JSON.parse(html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/)?.[1]);
check(Boolean(frontmatterDate), 'publication date is read from markdown frontmatter');
check(jsonLd.datePublished === frontmatterDate, 'JSON-LD publication date matches markdown frontmatter');
check(jsonLd.dateModified === frontmatterDate, 'JSON-LD modified date matches markdown frontmatter');

const wrongAnchor = publishedConnected.map((row) => row.value);
wrongAnchor[wrongAnchor.length - 1] += 1;
check(wrongAnchor.join(',') !== independent.slice(0, 10).map((row) => row.value).join(','), 'mutation test: a corrupted anchor goes red');

const corruptedAudit = structuredClone(auditData);
corruptedAudit.representatives[0][1] = [...corruptedAudit.representatives[0][0]];
check(!pageEngine.validateAudit(corruptedAudit).valid, 'mutation test: duplicate comparable edges make the page audit go red');

const corruptedConnected = [...connectedThroughTen];
corruptedConnected[10] += 1;
check(independentEuler(corruptedConnected, 10)[10] !== transformed[10], 'mutation test: a corrupted connected coefficient changes the Euler result');

console.log(`1..${assertions}`);
console.log(`# anchor: ${publishedConnected.map((row) => row.value).join(', ')}`);
console.log(`# extension: A293607(10) = ${independent[10].value}`);
console.log(`# transformed all-antichain coefficient at weight 10 = ${transformed[10]}`);
