// verify.mjs — "Half the Ways Home".  Exact checks behind the stratum
// (/strata/half-the-ways-home/): a cube (a die) rolled across the square grid
// can be brought back to a given cell in only HALF of its 24 orientations, and
// which half is fixed by a parity law.
//
//   node research/half-the-ways-home/verify.mjs
//
// Everything is exact: orientations are 3x3 INTEGER rotation matrices, group
// membership is decided by set-equality, and parity is the sign of an honest
// permutation of the four space-diagonals.  No floating point anywhere.
//
// THE OBJECT.  A cube sits on a cell of the infinite square grid in one of its
// 24 rotational orientations.  A "roll" tips it 90 degrees over one of its four
// bottom edges onto the orthogonally adjacent cell (N/S/E/W).  Starting from a
// fixed orientation at the origin, which (cell, orientation) states can it reach?
//
// THE FACTS this file proves:
//   [1] the four rolls generate the FULL rotation group of the cube (order 24);
//   [2] a single roll is an ODD permutation of the four space-diagonals;
//   [3] each roll flips the checkerboard colour (x+y) mod 2 of the cell;
//   [4] the orientations reachable back at the START cell are exactly 12, they
//       form a subgroup, and that subgroup is the tetrahedral group A4 (the EVEN
//       rotations) — never the other 12;
//   [5] the 12 forbidden-at-home orientations are exactly the 12 ODD ones;
//   [6] the checkerboard law: at cell (x,y) the reachable orientations are A4 if
//       x+y is even, the odd coset if x+y is odd — 12 either way, disjoint,
//       together all 24, but never more than half at any one cell;
//   [7] rolling around a single unit square (N,E,S,W) brings the die home in a
//       NON-identity orientation, of order 3 (a 120-degree turn about a body
//       diagonal) — the smallest witness of the whole phenomenon;
//   [8] the reachability COUNTS (states reachable in exactly / at most n rolls),
//       computed two independent ways, agree — reported as a computed artifact.
// See the verdict block at the bottom for what is PROVED vs merely OBSERVED.

'use strict';

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};

// ── exact 3x3 integer matrices (the cube's rotation group) ──────────────────
const I = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
const mul = (A, B) => A.map(r => [0, 1, 2].map(j => r[0] * B[0][j] + r[1] * B[1][j] + r[2] * B[2][j]));
const key = M => M.flat().join(',');

// A roll in direction d is a 90-degree rotation about the horizontal axis
// perpendicular to d (the die tips over that bottom edge).  With +x = East,
// +y = North, +z = Up:
//   roll North (+y): rotate about +x by -90   roll South (-y): about +x by +90
//   roll East  (+x): rotate about +y by +90   roll West  (-x): about +y by -90
const ROLL = {
  N: [[1, 0, 0], [0, 0, 1], [0, -1, 0]],
  S: [[1, 0, 0], [0, 0, -1], [0, 1, 0]],
  E: [[0, 0, 1], [0, 1, 0], [-1, 0, 0]],
  W: [[0, 0, -1], [0, 1, 0], [1, 0, 0]],
};
const STEP = { N: [0, 1], S: [0, -1], E: [1, 0], W: [-1, 0] };
const DIRS = ['N', 'S', 'E', 'W'];

console.log('Half the Ways Home — exact checks\n');

// ── [1] the four rolls generate the full rotation group (order 24) ──────────
console.log('[1] the four rolls generate the full cube rotation group');
const G = new Map([[key(I), I]]);
for (let grew = true; grew;) {
  grew = false;
  for (const M of [...G.values()]) for (const d of DIRS) {
    const P = mul(ROLL[d], M);
    if (!G.has(key(P))) { G.set(key(P), P); grew = true; }
  }
}
ok('the rolls generate a group of exactly 24 orientations', G.size === 24, `|G| = ${G.size}`);
// every generated matrix is a proper rotation (det = +1, integer orthogonal)
const det = M => M[0][0] * (M[1][1] * M[2][2] - M[1][2] * M[2][1])
  - M[0][1] * (M[1][0] * M[2][2] - M[1][2] * M[2][0])
  + M[0][2] * (M[1][0] * M[2][1] - M[1][1] * M[2][0]);
ok('every orientation is a proper rotation (det = +1)', [...G.values()].every(M => det(M) === 1));

// ── the four space-diagonals, and the sign of a permutation of them ─────────
// Each space-diagonal is a { v, -v } pair; label it by the representative whose
// first non-zero coordinate is +1.  A rotation permutes the four diagonals; its
// sign in that S4 action is the parity we care about.
const DIAG = [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1]];
const canon = v => {
  let w = v.slice();
  if (w[0] < 0 || (w[0] === 0 && (w[1] < 0 || (w[1] === 0 && w[2] < 0)))) w = w.map(x => -x);
  return w.join(',');
};
const DIAG_ID = DIAG.map(canon);
const permOfDiag = M => DIAG.map(d => {
  const img = canon([0, 1, 2].map(i => M[i][0] * d[0] + M[i][1] * d[1] + M[i][2] * d[2]));
  return DIAG_ID.indexOf(img);
});
const sign = p => { let s = 1; for (let i = 0; i < p.length; i++) for (let j = i + 1; j < p.length; j++) if (p[i] > p[j]) s = -s; return s; };
const isEven = M => sign(permOfDiag(M)) === 1;

// ── [2] a single roll is an ODD permutation of the diagonals ────────────────
console.log('\n[2] a single roll is an ODD rotation (odd permutation of the 4 space-diagonals)');
ok('roll N is odd (sign = -1)', sign(permOfDiag(ROLL.N)) === -1);
ok('all four rolls are odd', DIRS.every(d => sign(permOfDiag(ROLL[d])) === -1));
// among 24 rotations exactly 12 are even (A4) and 12 are odd — the S4 split
const evens = [...G.values()].filter(isEven);
ok('of the 24 orientations exactly 12 are even and 12 are odd', evens.length === 12, `even = ${evens.length}`);

// ── [3] each roll flips the checkerboard colour of the cell ─────────────────
console.log('\n[3] each roll flips the cell colour (x+y) mod 2 — so returning home needs an EVEN number of rolls');
ok('every step changes (x+y) parity by exactly 1', DIRS.every(d => (Math.abs(STEP[d][0] + STEP[d][1]) === 1)));

// ── BFS over (cell, orientation) states; collect orientations by cell parity ─
// Depth 16 is past saturation for the origin's orientation set and both cosets.
const orientAt = { even: new Set(), odd: new Set() }; // orientations seen at same/other colour cells
let frontier = new Map([[`0,0|${key(I)}`, { x: 0, y: 0, M: I }]]);
const seen = new Set(frontier.keys());
const note = st => { (((st.x + st.y) % 2 + 2) % 2 === 0 ? orientAt.even : orientAt.odd).add(key(st.M)); };
note({ x: 0, y: 0, M: I });
for (let n = 0; n < 16; n++) {
  const nf = new Map();
  for (const st of frontier.values()) for (const d of DIRS) {
    const M = mul(ROLL[d], st.M), x = st.x + STEP[d][0], y = st.y + STEP[d][1];
    const k = `${x},${y}|${key(M)}`;
    if (!seen.has(k)) { seen.add(k); nf.set(k, { x, y, M }); note({ x, y, M }); }
  }
  frontier = nf;
}

// ── [4] reachable-at-home = 12, a subgroup, = A4 (the even rotations) ────────
console.log('\n[4] back at the START cell only 12 of 24 orientations are reachable, and they are the group A4');
const home = [...orientAt.even].map(k => k); // keys of orientations reachable at same-colour cells
const homeSet = new Set(home);
ok('exactly 12 orientations are reachable at the start cell', home.length === 12, `${home.length} of 24`);
// closed under multiplication (a subgroup)
const asMat = k => k.split(',').map(Number).reduce((a, v, i) => { a[(i / 3) | 0][i % 3] = v; return a; }, [[0, 0, 0], [0, 0, 0], [0, 0, 0]]);
let closed = true;
for (const a of home) for (const b of home) if (!homeSet.has(key(mul(asMat(a), asMat(b))))) closed = false;
ok('the 12 reachable orientations are closed under composition (a subgroup)', closed);
ok('contains the identity', homeSet.has(key(I)));
// order profile {1:1, 2:3, 3:8} identifies A4 uniquely among order-12 groups
const order = M => { let P = M, k = 1; while (key(P) !== key(I)) { P = mul(P, M); k++; } return k; };
const profile = {};
for (const a of home) { const o = order(asMat(a)); profile[o] = (profile[o] || 0) + 1; }
ok('element-order profile is {1:1, 2:3, 3:8} — the tetrahedral group A4', profile[1] === 1 && profile[2] === 3 && profile[3] === 8 && !profile[4] && !profile[6], JSON.stringify(profile));
// and it IS exactly the even subgroup
ok('the 12 reachable orientations are exactly the 12 EVEN rotations (A4 by definition)',
  home.every(k => isEven(asMat(k))) && evens.length === 12 && home.length === 12);

// ── [5] the forbidden dozen are exactly the odd rotations ───────────────────
console.log('\n[5] the 12 orientations you can NEVER bring home are exactly the odd rotations');
const forbidden = [...G.values()].filter(M => !homeSet.has(key(M)));
ok('exactly 12 orientations are unreachable at the start cell', forbidden.length === 12);
ok('and they are exactly the 12 ODD rotations', forbidden.every(M => !isEven(M)));

// ── [6] the checkerboard law ────────────────────────────────────────────────
console.log('\n[6] the checkerboard law: which 12 depends only on the cell colour');
ok('same-colour cells (x+y even) admit exactly 12 orientations', orientAt.even.size === 12);
ok('other-colour cells (x+y odd) admit exactly 12 orientations', orientAt.odd.size === 12);
const inter = [...orientAt.even].filter(k => orientAt.odd.has(k));
ok('the two dozens are DISJOINT — no orientation is reachable at both colours', inter.length === 0);
ok('together they are all 24 orientations', orientAt.even.size + orientAt.odd.size === 24);
ok('the other-colour dozen are exactly the ODD rotations (a coset of A4)', [...orientAt.odd].every(k => !isEven(asMat(k))));

// ── [7] the smallest witness: a unit-square loop comes home turned ──────────
console.log('\n[7] roll once around a single square (N,E,S,W) and the die comes home TURNED');
let loop = I; for (const d of ['N', 'E', 'S', 'W']) loop = mul(ROLL[d], loop);
ok('the loop returns to the start cell but NOT to the start orientation', key(loop) !== key(I));
ok('the net turn has order 3 (a 120-degree rotation about a body diagonal)', order(loop) === 3, `order = ${order(loop)}`);
ok('the net turn is even (as it must be — an even number of rolls)', isEven(loop));

// ── [8] the reachability counts, two independent ways ───────────────────────
// Method A: the matrix BFS above.  Method B: an independent BFS that tracks the
// orientation as a pair of unit vectors (up, north) instead of a matrix.  If the
// two disagree on any term the counts are not trustworthy.
console.log('\n[8] reachability counts — states reachable in exactly / at most n rolls (two independent methods)');
function countMatrix(depth) {
  let fr = new Map([[`0,0|${key(I)}`, { x: 0, y: 0, M: I }]]);
  const sn = new Set(fr.keys());
  const exact = [1], cum = [1];
  for (let n = 1; n <= depth; n++) {
    const nf = new Map();
    for (const st of fr.values()) for (const d of DIRS) {
      const M = mul(ROLL[d], st.M), x = st.x + STEP[d][0], y = st.y + STEP[d][1], k = `${x},${y}|${key(M)}`;
      if (!sn.has(k)) { sn.add(k); nf.set(k, { x, y, M }); }
    }
    fr = nf; exact.push(nf.size); cum.push(sn.size);
  }
  return { exact, cum };
}
function countVectors(depth) {
  // orientation = (up, north) unit vectors; east = north x up.  Rolls rotate them.
  const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
  const neg = a => a.map(x => -x);
  const rot = (u, nn, d) => {
    const e = cross(nn, u);
    if (d === 'N') return [nn, neg(u)];
    if (d === 'S') return [neg(nn), u];
    if (d === 'E') return [neg(e), nn];
    return [e, nn]; // W
  };
  const k = (x, y, u, nn) => `${x},${y}|${u}|${nn}`;
  let fr = new Map([[k(0, 0, [0, 0, 1], [0, 1, 0]), { x: 0, y: 0, u: [0, 0, 1], nn: [0, 1, 0] }]]);
  const sn = new Set(fr.keys());
  const exact = [1], cum = [1];
  for (let n = 1; n <= depth; n++) {
    const nf = new Map();
    for (const st of fr.values()) for (const d of DIRS) {
      const [u, nn] = rot(st.u, st.nn, d), x = st.x + STEP[d][0], y = st.y + STEP[d][1], kk = k(x, y, u, nn);
      if (!sn.has(kk)) { sn.add(kk); nf.set(kk, { x, y, u, nn }); }
    }
    fr = nf; exact.push(nf.size); cum.push(sn.size);
  }
  return { exact, cum };
}
const DEPTH = 9;
const A = countMatrix(DEPTH), B = countVectors(DEPTH);
ok('the two independent methods agree on "reachable in exactly n rolls"', JSON.stringify(A.exact) === JSON.stringify(B.exact));
ok('the two independent methods agree on "reachable in at most n rolls"', JSON.stringify(A.cum) === JSON.stringify(B.cum));
console.log(`      exact(n=0..${DEPTH}) : ${A.exact.join(', ')}`);
console.log(`      cumulative        : ${A.cum.join(', ')}`);
console.log('      (an OEIS search on 2026-07-03 did not find either run catalogued; claimed only as "not found", never "provably new")');

// ── [9] sanity: the die can reach EVERY cell (freedom is in position) ───────
console.log('\n[9] sanity — the constraint is on orientation, not position: every cell is reachable');
// reachable cells at BFS depth D are exactly the correct-parity cells within taxicab D
let cells = new Set(['0,0']); let fr2 = [[0, 0]];
const D = 8;
for (let n = 0; n < D; n++) {
  const nx = [];
  for (const [x, y] of fr2) for (const d of DIRS) { const a = x + STEP[d][0], b = y + STEP[d][1]; if (!cells.has(`${a},${b}`)) { cells.add(`${a},${b}`); nx.push([a, b]); } }
  fr2 = nx;
}
let allParityCellsHit = true;
for (let x = -D; x <= D; x++) for (let y = -D; y <= D; y++) {
  if (Math.abs(x) + Math.abs(y) <= D && (Math.abs(x) + Math.abs(y)) % 2 === 0) { if (!cells.has(`${x},${y}`)) allParityCellsHit = false; }
}
ok('every even-parity cell within taxicab distance 8 is reachable (position is unconstrained)', allParityCellsHit);

// ── verdict ─────────────────────────────────────────────────────────────────
// PROVED (exactly, by finite computation over the 24-element group):
//   - a die rolled on the grid can occupy at most 12 of its 24 orientations at
//     any one cell; back at its start cell those 12 are the tetrahedral group A4
//     (the even rotations), and the other 12 (the odd ones) are forever out of
//     reach; on the opposite-colour cells the roles swap.  The mechanism is a
//     single parity law: one roll flips both the cell colour and the rotation's
//     parity, so cell colour and orientation parity are locked together.
//   - the position is entirely unconstrained: the die reaches every cell.
// OBSERVED, NOT CLAIMED AS NEW:
//   - the specific integer runs in [8] were not found in OEIS on 2026-07-03;
//     that is an absence-of-evidence note, not a novelty proof.  The A4/parity
//     structure itself is classical group theory (S4 acting on the four space-
//     diagonals; the alternating subgroup), here made operable, not discovered.
console.log(`\n${fails === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${fails} failed.`);
process.exit(fails === 0 ? 0 : 1);
