#!/usr/bin/env node

/*
 * Exhaustive verifier for "Eleven Moves From Anywhere".
 *
 * Convention: the DBL corner is fixed in both position and orientation. The
 * remaining state is a permutation of seven corners and six independent corner
 * twists. U, R and F generate the rotation-quotiented pocket-cube graph.
 */

import assert from 'node:assert/strict';

const POSITIONS = [0, 1, 2, 3, 4, 5, 7];
const POSITION_CODE = new Int8Array(8).fill(-1);
POSITIONS.forEach((position, code) => {
  POSITION_CODE[position] = code;
});

const FACTORIAL = [1];
for (let n = 1; n <= 8; n += 1) FACTORIAL[n] = FACTORIAL[n - 1] * n;

const PERMUTATIONS = FACTORIAL[7];
const ORIENTATIONS = 3 ** 6;
const STATES = PERMUTATIONS * ORIENTATIONS;

// newCorner[position] = oldCorner[cp[position]]
// newTwist[position] = oldTwist[cp[position]] + co[position] (mod 3)
// Cubie order: URF UFL ULB UBR DFR DLF DBL DRB.
const QUARTER_TURNS = [
  {
    name: 'U',
    cp: [3, 0, 1, 2, 4, 5, 6, 7],
    co: [0, 0, 0, 0, 0, 0, 0, 0],
  },
  {
    name: 'R',
    cp: [4, 1, 2, 0, 7, 5, 6, 3],
    co: [2, 0, 0, 1, 1, 0, 0, 2],
  },
  {
    name: 'F',
    cp: [1, 5, 2, 3, 0, 4, 6, 7],
    co: [1, 2, 0, 0, 2, 1, 0, 0],
  },
];

function rankPermutation(permutation) {
  let rank = 0;
  for (let i = 0; i < 7; i += 1) {
    let smallerToRight = 0;
    for (let j = i + 1; j < 7; j += 1) {
      if (permutation[j] < permutation[i]) smallerToRight += 1;
    }
    rank += smallerToRight * FACTORIAL[6 - i];
  }
  return rank;
}

function unrankPermutation(rank) {
  const available = [0, 1, 2, 3, 4, 5, 6];
  const permutation = new Uint8Array(7);
  let remainder = rank;
  for (let i = 0; i < 7; i += 1) {
    const place = FACTORIAL[6 - i];
    const digit = Math.floor(remainder / place);
    remainder %= place;
    permutation[i] = available.splice(digit, 1)[0];
  }
  return permutation;
}

function unrankOrientation(rank) {
  const orientation = new Uint8Array(8);
  let twistSum = 0;
  let remainder = rank;
  for (let i = 5; i >= 0; i -= 1) {
    const twist = remainder % 3;
    remainder = Math.floor(remainder / 3);
    orientation[POSITIONS[i]] = twist;
    twistSum += twist;
  }
  orientation[POSITIONS[6]] = (3 - (twistSum % 3)) % 3;
  return orientation;
}

function rankOrientation(orientation) {
  let rank = 0;
  for (let i = 0; i < 6; i += 1) {
    rank = rank * 3 + orientation[POSITIONS[i]];
  }
  return rank;
}

function buildMoveTables() {
  const permutationQuarter = QUARTER_TURNS.map(() => new Uint16Array(PERMUTATIONS));
  const orientationQuarter = QUARTER_TURNS.map(() => new Uint16Array(ORIENTATIONS));

  for (let rank = 0; rank < PERMUTATIONS; rank += 1) {
    const permutation = unrankPermutation(rank);
    const full = new Uint8Array(8);
    full[6] = 6;
    for (let i = 0; i < 7; i += 1) {
      full[POSITIONS[i]] = POSITIONS[permutation[i]];
    }

    QUARTER_TURNS.forEach((move, moveIndex) => {
      const moved = new Uint8Array(7);
      for (let i = 0; i < 7; i += 1) {
        const sourcePiece = full[move.cp[POSITIONS[i]]];
        moved[i] = POSITION_CODE[sourcePiece];
      }
      permutationQuarter[moveIndex][rank] = rankPermutation(moved);
    });
  }

  for (let rank = 0; rank < ORIENTATIONS; rank += 1) {
    const orientation = unrankOrientation(rank);
    QUARTER_TURNS.forEach((move, moveIndex) => {
      const moved = new Uint8Array(8);
      for (let position = 0; position < 8; position += 1) {
        moved[position] =
          (orientation[move.cp[position]] + move.co[position]) % 3;
      }
      orientationQuarter[moveIndex][rank] = rankOrientation(moved);
    });
  }

  const permutationTurns = Array.from({ length: 9 }, () =>
    new Uint16Array(PERMUTATIONS),
  );
  const orientationTurns = Array.from({ length: 9 }, () =>
    new Uint16Array(ORIENTATIONS),
  );

  for (let face = 0; face < 3; face += 1) {
    for (let turns = 1; turns <= 3; turns += 1) {
      const moveIndex = face * 3 + turns - 1;
      for (let rank = 0; rank < PERMUTATIONS; rank += 1) {
        let moved = rank;
        for (let step = 0; step < turns; step += 1) {
          moved = permutationQuarter[face][moved];
        }
        permutationTurns[moveIndex][rank] = moved;
      }
      for (let rank = 0; rank < ORIENTATIONS; rank += 1) {
        let moved = rank;
        for (let step = 0; step < turns; step += 1) {
          moved = orientationQuarter[face][moved];
        }
        orientationTurns[moveIndex][rank] = moved;
      }
    }
  }

  return { permutationTurns, orientationTurns };
}

function breadthFirstSearch(tables, moveIndices) {
  const distancePlusOne = new Uint8Array(STATES);
  const queue = new Uint32Array(STATES);
  const histogram = [];
  let head = 0;
  let tail = 1;
  let diameter = 0;

  distancePlusOne[0] = 1;
  queue[0] = 0;
  histogram[0] = 1;

  while (head < tail) {
    const state = queue[head];
    head += 1;
    const depth = distancePlusOne[state] - 1;
    const permutation = Math.floor(state / ORIENTATIONS);
    const orientation = state - permutation * ORIENTATIONS;

    for (let i = 0; i < moveIndices.length; i += 1) {
      const move = moveIndices[i];
      const next =
        tables.permutationTurns[move][permutation] * ORIENTATIONS +
        tables.orientationTurns[move][orientation];
      if (distancePlusOne[next] !== 0) continue;

      const nextDepth = depth + 1;
      distancePlusOne[next] = nextDepth + 1;
      queue[tail] = next;
      tail += 1;
      histogram[nextDepth] = (histogram[nextDepth] || 0) + 1;
      if (nextDepth > diameter) diameter = nextDepth;
    }
  }

  return {
    count: tail,
    diameter,
    histogram,
  };
}

const expectedHtmHistogram = [
  1, 9, 54, 321, 1847, 9992, 50136, 227536, 870072, 1887748, 623800, 2644,
];
const expectedQtmHistogram = [
  1, 6, 27, 120, 534, 2256, 8969, 33058, 114149, 360508, 930588, 1350852,
  782536, 90280, 276,
];

console.log('Building standalone U, R, F coordinate move tables...');
const tables = buildMoveTables();

console.log('Running exhaustive half-turn-metric BFS...');
const htm = breadthFirstSearch(tables, [0, 1, 2, 3, 4, 5, 6, 7, 8]);

console.log('Running exhaustive quarter-turn-metric BFS...');
const qtm = breadthFirstSearch(tables, [0, 2, 3, 5, 6, 8]);

const formulaCount = FACTORIAL[7] * 3 ** 6;
const spatialOrientations = 6 * 4;
const rawStickerStates = FACTORIAL[8] * 3 ** 7;
const rotationQuotient = rawStickerStates / spatialOrientations;
const farthestPercentage = htm.histogram[htm.diameter] / htm.count * 100;

assert.equal(formulaCount, 3_674_160, '7! * 3^6 position formula changed');
assert.equal(spatialOrientations, 24, 'cube orientation count changed');
assert.equal(rawStickerStates, 88_179_840, 'unquotiented state count changed');
assert.equal(rotationQuotient, formulaCount, 'rotation quotient disagrees with fixed-corner count');
assert.equal(htm.count, formulaCount, 'HTM BFS did not reach every fixed-corner state');
assert.equal(qtm.count, formulaCount, 'QTM BFS did not reach every fixed-corner state');
assert.equal(htm.diameter, 11, 'HTM diameter is not 11');
assert.equal(qtm.diameter, 14, 'QTM diameter is not 14');
assert.equal(htm.histogram[0], 1, 'HTM depth zero must contain only solved');
assert.equal(qtm.histogram[0], 1, 'QTM depth zero must contain only solved');
assert.equal(
  htm.histogram.reduce((sum, count) => sum + count, 0),
  formulaCount,
  'HTM histogram does not sum to the state count',
);
assert.equal(
  qtm.histogram.reduce((sum, count) => sum + count, 0),
  formulaCount,
  'QTM histogram does not sum to the state count',
);
assert.deepEqual(htm.histogram, expectedHtmHistogram, 'HTM histogram drifted');
assert.deepEqual(qtm.histogram, expectedQtmHistogram, 'QTM histogram drifted');

console.log(`Fixed-corner permutations: ${FACTORIAL[7].toLocaleString('en-US')}`);
console.log(`Independent corner orientations: ${ORIENTATIONS.toLocaleString('en-US')}`);
console.log(`Reachable positions: ${formulaCount.toLocaleString('en-US')} = 7! * 3^6`);
console.log(
  `Rotation quotient: ${rawStickerStates.toLocaleString('en-US')} / ` +
  `${spatialOrientations} = ${rotationQuotient.toLocaleString('en-US')}`,
);
console.log(`HTM histogram: ${htm.histogram.join(', ')}`);
console.log(`HTM histogram sum: ${htm.count.toLocaleString('en-US')}`);
console.log(`HTM diameter: ${htm.diameter}`);
console.log(`HTM depth-${htm.diameter} positions: ${htm.histogram[htm.diameter].toLocaleString('en-US')}`);
console.log(`HTM farthest-state share: ${farthestPercentage.toFixed(3)}%`);
console.log(`QTM histogram: ${qtm.histogram.join(', ')}`);
console.log(`QTM histogram sum: ${qtm.count.toLocaleString('en-US')}`);
console.log(`QTM diameter: ${qtm.diameter}`);
console.log('All exhaustive checks passed.');
