// verify.mjs: the mathematical checks listed below, recomputed offline. Run: node research/the-mutilated-chessboard/verify.mjs
// (exit 0 = all pass). Tileability is DECIDED by exact bipartite
// matching, and the positive direction is exhibited as a concrete witness tiling.
//
// What it checks:
//   A. The colouring: a full board has 32 light + 32 dark; the two opposite corners are the
//      SAME colour, so removing them leaves 30 vs 32.
//   B. The invariant: every domino covers exactly one light + one dark square, so any tiling
//      covers equal numbers — checked over every adjacent pair on the board.
//   C. The impossibility, DECIDED: the mutilated board (minus two opposite corners) has no
//      perfect matching — maximum matching is 30 dominoes, leaving two squares forever
//      uncovered. Both diagonals' corner pairs, checked.
//   D. The sharp dividing line, EXHAUSTIVE: across all 2016 ways to remove two squares from
//      the 8×8 board, the region is domino-tileable IF AND ONLY IF the two removed squares
//      are opposite colours. (Necessity = the colouring argument; sufficiency = Gomory.)
//   E. Gomory's construction, as a WITNESS: the Hamiltonian-cycle tiling actually tiles the
//      board minus one light + one dark square — for a sample of removed pairs, the produced
//      domino list is verified to cover the region exactly.
//   F. A separate count: the intact 8×8 board has 12 988 816 domino tilings (Kasteleyn),
//      recomputed by profile dynamic programming. This is not the size of a search
//      on the mutilated board.

import {
  N, color, fullBoard, boardMinus, colorCounts, adjacent,
  maxMatching, isTileable, hamiltonianCycle, gomoryTiling, tilingCovers,
} from './chessboard.mjs';

let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  — ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL ${name}${detail ? '  — ' + detail : ''}`); }
}

console.log('\nA. The 2-colouring and the two corners');
{
  const full = colorCounts(fullBoard());
  check('full 8×8 board is 32 light + 32 dark', full.light === 32 && full.dark === 32,
    `${full.light}+${full.dark}`);
  // the four corners
  const corners = { '(0,0)': color(0, 0), '(7,0)': color(7, 0), '(0,7)': color(0, 7), '(7,7)': color(7, 7) };
  check('opposite corners (0,0) & (7,7) share a colour', corners['(0,0)'] === corners['(7,7)'],
    `both colour ${corners['(0,0)']}`);
  check('opposite corners (7,0) & (0,7) share a colour', corners['(7,0)'] === corners['(0,7)'],
    `both colour ${corners['(7,0)']}`);
  const mut = colorCounts(boardMinus([[0, 0], [7, 7]]));
  check('board minus (0,0)+(7,7) is 30 vs 32', mut.light === 30 && mut.dark === 32,
    `${mut.light} light, ${mut.dark} dark`);
}

console.log('\nB. The invariant: every domino is one light + one dark');
{
  // enumerate every adjacent pair on the full board and confirm opposite colours
  const board = fullBoard();
  let pairs = 0, balanced = 0;
  for (let i = 0; i < board.length; i++)
    for (let j = i + 1; j < board.length; j++)
      if (adjacent(board[i], board[j])) {
        pairs++;
        if (color(...board[i]) !== color(...board[j])) balanced++;
      }
  check('every adjacent pair (every possible domino) covers one of each colour',
    pairs === balanced && pairs === 112, `${balanced}/${pairs} balanced (112 horizontal+vertical dominoes)`);
}

console.log('\nC. The impossibility, decided by exact matching');
{
  for (const [a, b] of [[[0, 0], [7, 7]], [[7, 0], [0, 7]]]) {
    const region = boardMinus([a, b]);
    const m = maxMatching(region);
    check(`board minus (${a})+(${b}): NO perfect tiling`, !isTileable(region),
      `max matching = ${m.size} dominoes, 62 squares → 2 left uncovered`);
    const counts = colorCounts(region);
    const covered = new Set(m.pairs.flat().map((s) => s.join(',')));
    const remaining = region.filter((s) => !covered.has(s.join(',')));
    const free = colorCounts(remaining);
    const minority = counts.light < counts.dark ? 'light' : 'dark';
    const majority = minority === 'light' ? 'dark' : 'light';
    check(`  …and the obstruction is exactly the colour deficit`,
      m.size === 30 && m.pairs.length === 30 && covered.size === 60
        && tilingCovers(m.pairs, region.filter((s) => covered.has(s.join(',')))).ok
        && counts[minority] === 30 && counts[majority] === 32
        && free[minority] === 0 && free[majority] === 2,
      `matching saturates the 30 ${minority} squares, stranding 2 ${majority}`);
  }
}

console.log('\nD. The dividing line, over ALL 2016 two-square removals');
{
  const board = fullBoard();
  let total = 0, agree = 0, sameColourTileable = 0, oppColourUntileable = 0;
  for (let i = 0; i < board.length; i++)
    for (let j = i + 1; j < board.length; j++) {
      total++;
      const region = boardMinus([board[i], board[j]]);
      const tile = isTileable(region);
      const opposite = color(...board[i]) !== color(...board[j]);
      if (tile === opposite) agree++;
      if (!opposite && tile) sameColourTileable++;
      if (opposite && !tile) oppColourUntileable++;
    }
  check('all 2016 removals enumerated', total === 2016, `${total}`);
  check('tileable ⟺ the two removed squares are OPPOSITE colours — no exceptions',
    agree === total && sameColourTileable === 0 && oppColourUntileable === 0,
    `${agree}/${total} agree; same-colour-yet-tileable=${sameColourTileable}, opp-colour-yet-blocked=${oppColourUntileable}`);
}

console.log('\nE. Gomory: the positive direction as an explicit witness');
{
  const cyc = hamiltonianCycle(N);
  // it really is a Hamiltonian cycle
  const distinct = new Set(cyc.map((s) => s.join(',')));
  let consecOk = true;
  for (let k = 0; k < cyc.length; k++) if (!adjacent(cyc[k], cyc[(k + 1) % cyc.length])) consecOk = false;
  check('Hamiltonian cycle: 64 distinct squares, every step (incl. wrap) adjacent',
    distinct.size === 64 && cyc.length === 64 && consecOk, `${distinct.size} squares`);
  let altOk = true;
  for (let k = 0; k < cyc.length; k++)
    if (color(...cyc[k]) === color(...cyc[(k + 1) % cyc.length])) altOk = false;
  check('colours strictly alternate around the cycle', altOk);

  // a spread of light/dark removals, including the "fixed" version of the impossible puzzle:
  // remove (0,0) [light] and a DARK corner-neighbour, and watch it tile.
  const samples = [
    [[0, 0], [1, 0]], [[0, 0], [7, 6]], [[4, 4], [3, 4]], [[2, 6], [5, 2]], [[6, 0], [0, 7]],
  ];
  let allWitnessed = true;
  for (const pair of samples) {
    // order light-first, dark-second (the construction's contract)
    const [L, D] = color(...pair[0]) === 0 ? pair : [pair[1], pair[0]];
    if (color(...L) !== 0 || color(...D) !== 1) { allWitnessed = false; console.log(`     sample ${pair} is not a light+dark pair`); continue; }
    const region = boardMinus([L, D]);
    const t = gomoryTiling(L, D);
    const cov = tilingCovers(t, region);
    if (!cov.ok || t.length !== 31) { allWitnessed = false; console.log(`     witness failed for ${L}/${D}: ${cov.why || t.length + ' dominoes'}`); }
  }
  check('Gomory tiling covers board minus {one light, one dark} exactly (31 dominoes), samples',
    allWitnessed, `${samples.length} removals witnessed`);
}

console.log('\nF. A separate count: tilings of the intact board');
{
  // Number of domino tilings of the intact 8×8 board (Kasteleyn 1961): 12 988 816.
  // Recompute by the row transfer matrix (profile DP over 2^8 column states).
  const n = 8;
  // Clean broken-profile DP: count perfect domino tilings of a rows×cols grid.
  function dominoTilings(rows, cols) {
    // states: bitmask over `cols` of cells protruding into the current cell's row.
    let cur = new Array(1 << cols).fill(0n); cur[0] = 1n;
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) {
        const next = new Array(1 << cols).fill(0n);
        for (let mask = 0; mask < (1 << cols); mask++) {
          const ways = cur[mask]; if (ways === 0n) continue;
          const bit = 1 << c;
          if (mask & bit) {
            next[mask ^ bit] += ways;        // cell already covered from above
          } else {
            // vertical: cover this cell and protrude downward
            next[mask | bit] += ways;
            // horizontal: cover this cell and the next column (must be free & exist)
            if (c + 1 < cols && !(mask & (1 << (c + 1)))) next[mask | (1 << (c + 1))] += ways;
          }
        }
        cur = next;
      }
    }
    return cur[0];
  }
  const count = dominoTilings(n, n);
  check('domino tilings of the INTACT 8×8 board = 12,988,816 (Kasteleyn)', count === 12988816n,
    `${count.toLocaleString('en-US')} tilings of the intact board`);
  // sanity: a 2×2 has 2 tilings, 2×n has Fibonacci-ish, full board nonzero
  check('  DP sanity: 2×2 → 2, 2×3 → 3, 2×4 → 5 (Fibonacci)',
    dominoTilings(2, 2) === 2n && dominoTilings(2, 3) === 3n && dominoTilings(2, 4) === 5n);
}

console.log(`\n${fail === 0 ? '✓' : '✗'} the-mutilated-chessboard: ${pass} passed, ${fail} failed.\n`);
process.exit(fail === 0 ? 0 : 1);
