#!/usr/bin/env node

import assert from 'node:assert/strict';

const GRAPHS = {
  odd: {
    name: 'pentagon with a chord',
    n: 5,
    anchor: 0,
    edges: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0], [0, 2]]
  },
  even: {
    name: 'K2,3',
    n: 5,
    anchor: 0,
    edges: [[0, 2], [0, 3], [0, 4], [1, 2], [1, 3], [1, 4]]
  },
  theta0: {
    name: 'theta_0',
    n: 7,
    anchor: 0,
    // A hexagon 0-1-2-3-4-5-0 plus the two-edge path 0-6-3.
    // Equivalently, vertices 0 and 3 are joined by paths of lengths 3, 3, and 2.
    edges: [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [0, 6], [6, 3]]
  }
};

function factorial(n) {
  let value = 1;
  for (let i = 2; i <= n; i += 1) value *= i;
  return value;
}

function adjacency(graph) {
  const adjacent = Array.from({ length: graph.n }, () => []);
  for (const [a, b] of graph.edges) {
    assert.ok(a >= 0 && a < graph.n && b >= 0 && b < graph.n, 'edge endpoint out of range');
    assert.notEqual(a, b, 'loops are not allowed');
    adjacent[a].push(b);
    adjacent[b].push(a);
  }
  return adjacent;
}

function allPermutations(n) {
  const current = Array.from({ length: n }, (_, i) => i);
  const result = [];

  function visit(position) {
    if (position === n) {
      result.push(current.join(','));
      return;
    }
    for (let i = position; i < n; i += 1) {
      [current[position], current[i]] = [current[i], current[position]];
      visit(position + 1);
      [current[position], current[i]] = [current[i], current[position]];
    }
  }

  visit(0);
  assert.equal(result.length, factorial(n), 'permutation generator returned the wrong count');
  assert.equal(new Set(result).size, result.length, 'permutation generator returned duplicates');
  return result;
}

function inversionParity(state) {
  const tiles = state.filter((label) => label !== 0);
  let inversions = 0;
  for (let i = 0; i < tiles.length; i += 1) {
    for (let j = i + 1; j < tiles.length; j += 1) {
      if (tiles[i] > tiles[j]) inversions += 1;
    }
  }
  return inversions % 2;
}

function isBipartite(adjacent) {
  const colour = Array(adjacent.length).fill(-1);
  for (let root = 0; root < adjacent.length; root += 1) {
    if (colour[root] !== -1) continue;
    colour[root] = 0;
    const queue = [root];
    for (let head = 0; head < queue.length; head += 1) {
      const v = queue[head];
      for (const next of adjacent[v]) {
        if (colour[next] === -1) {
          colour[next] = 1 - colour[v];
          queue.push(next);
        } else if (colour[next] === colour[v]) {
          return false;
        }
      }
    }
  }
  return true;
}

function isTwoConnected(adjacent) {
  if (adjacent.length < 3) return false;
  for (let removed = 0; removed < adjacent.length; removed += 1) {
    const start = removed === 0 ? 1 : 0;
    const seen = new Set([start]);
    const queue = [start];
    for (let head = 0; head < queue.length; head += 1) {
      for (const next of adjacent[queue[head]]) {
        if (next !== removed && !seen.has(next)) {
          seen.add(next);
          queue.push(next);
        }
      }
    }
    if (seen.size !== adjacent.length - 1) return false;
  }
  return true;
}

function isSingleCycle(graph, adjacent) {
  return graph.edges.length === graph.n && adjacent.every((neighbours) => neighbours.length === 2);
}

function analyse(graph) {
  const adjacent = adjacency(graph);
  const permutations = allPermutations(graph.n);
  const componentOf = new Map();
  const components = [];

  for (const startKey of permutations) {
    if (componentOf.has(startKey)) continue;

    const id = components.length;
    const queue = [startKey];
    componentOf.set(startKey, id);
    let anchored = 0;
    const anchoredParity = [0, 0];

    for (let head = 0; head < queue.length; head += 1) {
      const key = queue[head];
      const state = key.split(',').map(Number);
      const hole = state.indexOf(0);

      if (hole === graph.anchor) {
        anchored += 1;
        anchoredParity[inversionParity(state)] += 1;
      }

      for (const nextHole of adjacent[hole]) {
        const next = state.slice();
        [next[hole], next[nextHole]] = [next[nextHole], next[hole]];
        const nextKey = next.join(',');
        if (!componentOf.has(nextKey)) {
          componentOf.set(nextKey, id);
          queue.push(nextKey);
        }
      }
    }

    components.push({
      states: queue.length,
      anchored,
      anchoredEven: anchoredParity[0],
      anchoredOdd: anchoredParity[1]
    });
  }

  return {
    name: graph.name,
    vertices: graph.n,
    edges: graph.edges.length,
    totalStates: permutations.length,
    anchoredTotal: permutations.filter((key) => Number(key.split(',')[graph.anchor]) === 0).length,
    bipartite: isBipartite(adjacent),
    twoConnected: isTwoConnected(adjacent),
    singleCycle: isSingleCycle(graph, adjacent),
    components
  };
}

const odd = analyse(GRAPHS.odd);
const even = analyse(GRAPHS.even);
const theta0 = analyse(GRAPHS.theta0);

assert.deepEqual(
  {
    total: odd.totalStates,
    bipartite: odd.bipartite,
    twoConnected: odd.twoConnected,
    cycle: odd.singleCycle,
    componentSizes: odd.components.map((component) => component.states),
    anchoredSizes: odd.components.map((component) => component.anchored)
  },
  {
    total: 120,
    bipartite: false,
    twoConnected: true,
    cycle: false,
    componentSizes: [120],
    anchoredSizes: [24]
  }
);

assert.deepEqual(
  {
    total: even.totalStates,
    bipartite: even.bipartite,
    twoConnected: even.twoConnected,
    cycle: even.singleCycle,
    componentSizes: even.components.map((component) => component.states).sort((a, b) => a - b),
    anchoredSizes: even.components.map((component) => component.anchored).sort((a, b) => a - b)
  },
  {
    total: 120,
    bipartite: true,
    twoConnected: true,
    cycle: false,
    componentSizes: [60, 60],
    anchoredSizes: [12, 12]
  }
);

assert.equal(theta0.vertices, 7);
assert.equal(theta0.edges, 8);
assert.equal(theta0.totalStates, factorial(7));
assert.equal(theta0.anchoredTotal, factorial(6));
assert.equal(theta0.bipartite, false);
assert.equal(theta0.twoConnected, true);
assert.equal(theta0.singleCycle, false);
assert.equal(theta0.components.length, 6);
assert.deepEqual(theta0.components.map((component) => component.states), Array(6).fill(840));
assert.deepEqual(theta0.components.map((component) => component.anchored), Array(6).fill(120));
assert.deepEqual(theta0.components.map((component) => component.anchoredEven), Array(6).fill(60));
assert.deepEqual(theta0.components.map((component) => component.anchoredOdd), Array(6).fill(60));
assert.equal(theta0.components.reduce((sum, component) => sum + component.states, 0), 5040);
assert.equal(theta0.components.reduce((sum, component) => sum + component.anchored, 0), 720);

for (const result of [odd, even, theta0]) {
  console.log(`\n${result.name}`);
  console.log(`  graph: ${result.vertices} vertices, ${result.edges} edges`);
  console.log(`  hypotheses: 2-connected=${result.twoConnected}, single-cycle=${result.singleCycle}, bipartite=${result.bipartite}`);
  console.log(`  full state graph: ${result.totalStates} states, ${result.components.length} component(s)`);
  console.log(`  full component sizes: ${result.components.map((component) => component.states).join(', ')}`);
  console.log(`  hole-at-home arrangements: ${result.anchoredTotal}`);
  console.log(`  hole-at-home counts per component: ${result.components.map((component) => component.anchored).join(', ')}`);
  console.log(`  anchored even/odd tile parities: ${result.components.map((component) => `${component.anchoredEven}/${component.anchoredOdd}`).join(', ')}`);
}

console.log('\nPASS: exhaustive BFS reproduced every published page count.');
console.log('Counting note: theta_0 has six full components of 840 states;');
console.log('each component contains 120 arrangements when the hole is returned to its chosen home.');
