// Verification harness for the abelian sandpile engine. Every claim the stratum
// page makes is checked here first, against brute force or a known answer.
// Run:  node research/abelian-sandpile/verify.mjs
import {
  nbrTable, stabilize, stabilizeByScan, cmax, identity, add, isRecurrent,
  singleSource, spanningTrees,
} from './sandpile.mjs';

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  (cond ? pass++ : fail++);
  console.log(`  ${cond ? 'PASS' : 'FAIL'}  ${name}${extra ? '  — ' + extra : ''}`);
};
const eqArr = (a, b) => { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; return true; };
function rng(seed) { let s = seed >>> 0; return () => (s = (s * 1664525 + 1013904223) >>> 0) / 4294967296; }

// ===== 1. Abelian property: order of toppling is irrelevant =====
console.log('\n1. ABELIAN PROPERTY (Dhar 1990): final config AND odometer are order-independent');
{
  const r = rng(7);
  let allEqConfig = true, allEqOdo = true;
  for (let trial = 0; trial < 200; trial++) {
    const W = 3 + (r() * 6 | 0), H = 3 + (r() * 6 | 0), N = W * H;
    const nbr = nbrTable(W, H);
    const start = new Int32Array(N);
    for (let i = 0; i < N; i++) start[i] = (r() * 9) | 0;   // 0..8, deliberately unstable
    // schedule A: queue
    const cA = Int32Array.from(start); const oA = stabilize(W, H, cA, nbr).odo;
    // schedule B: scan a random permutation
    const perm = [...Array(N).keys()];
    for (let i = N - 1; i > 0; i--) { const j = (r() * (i + 1)) | 0; [perm[i], perm[j]] = [perm[j], perm[i]]; }
    const cB = Int32Array.from(start); const oB = stabilizeByScan(W, H, cB, perm, nbr).odo;
    if (!eqArr(cA, cB)) allEqConfig = false;
    if (!eqArr(oA, oB)) allEqOdo = false;
  }
  ok('200 random starts: queue-order final == scan-order final', allEqConfig);
  ok('200 random starts: odometer (topple counts) identical too', allEqOdo);
}

// ===== 2. Matrix-Tree theorem: |sandpile group| = #spanning trees = det(reduced Laplacian) =====
// Verified against a brute-force count of recurrent configurations (burning test).
console.log('\n2. MATRIX-TREE: det(reduced Laplacian) == #recurrent configs == |sandpile group|');
function countRecurrentBrute(W, H) {
  const N = W * H, nbr = nbrTable(W, H);
  // each cell height 0..3 (stable); count those passing the burning test
  let count = 0;
  const c = new Int32Array(N);
  const total = 4 ** N;
  for (let code = 0; code < total; code++) {
    let x = code;
    for (let i = 0; i < N; i++) { c[i] = x & 3; x >>= 2; }
    if (isRecurrent(W, H, c, nbr)) count++;
  }
  return count;
}
for (const [W, H] of [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]) {
  const det = spanningTrees(W, H);          // BigInt, exact
  const brute = BigInt(countRecurrentBrute(W, H));
  ok(`${W}x${H}: det(Δ)=${det}  recurrent-count=${brute}`, det === brute);
}
// A couple of larger ones by determinant only (no brute force) for the record.
for (const [W, H] of [[3,4],[4,4],[5,5],[8,8]])
  console.log(`     ${W}x${H}: det(Δ) = #spanning trees = |group| = ${spanningTrees(W, H)}`);

// ===== 3. The identity element =====
console.log('\n3. IDENTITY (Creutz 1991): e is recurrent, idempotent, and neutral');
{
  const r = rng(99);
  for (const [W, H] of [[3,3],[5,5],[8,8],[12,12]]) {
    const nbr = nbrTable(W, H);
    const e = identity(W, H, nbr);
    const rec = isRecurrent(W, H, e, nbr);
    const idem = eqArr(add(W, H, e, e, nbr), e);                 // e ⊕ e = e
    // neutral on random recurrent configs: r ⊕ e = r
    let neutral = true;
    for (let t = 0; t < 8; t++) {
      // build a recurrent config: max-stable plus a random pile, stabilised, then +e until recurrent-stable
      const c = cmax(W, H);
      for (let k = 0; k < W * H; k++) c[k] += (r() * 30) | 0;
      stabilize(W, H, c, nbr);                                    // now stable; it is recurrent (max-stable + grains)
      const c2 = add(W, H, c, e, nbr);
      if (!eqArr(c2, c)) neutral = false;
    }
    ok(`${W}x${H}: identity recurrent=${rec}, e⊕e=e=${idem}, r⊕e=r=${neutral}`, rec && idem && neutral);
  }
}

// ===== 4. Single source: conservation of grains =====
console.log('\n4. SINGLE SOURCE: grains in == grains remaining + grains lost to sink');
{
  for (const n of [1000, 5000, 20000]) {
    const W = 121, H = 121, cx = 60, cy = 60, nbr = nbrTable(W, H);
    const c0 = new Int32Array(W * H); c0[cx + cy * W] = n;
    const odo = new Int32Array(W * H);
    // re-run with odometer to compute loss
    const c = Int32Array.from(c0);
    const res = stabilize(W, H, c, nbr);
    // loss = sum over cells of topples * (#edges to sink)
    let lost = 0, remain = 0;
    for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
      const i = x + y * W;
      lost += res.odo[i] * (4 - nbr[i].length);
      remain += c[i];
    }
    const reachedBoundary = (() => { // sanity: pattern must not touch the wall
      for (let x = 0; x < W; x++) if (c[x] || c[x + (H-1)*W]) return true;
      for (let y = 0; y < H; y++) if (c[y*W] || c[y*W + W-1]) return true;
      return false;
    })();
    ok(`n=${n}: ${remain}+${lost} == ${n}`, remain + lost === n, `topples=${res.total}, boundary-clear=${!reachedBoundary}`);
  }
}

// ===== 5. Known small spanning-tree counts (cross-check the determinant) =====
// 1x1 grid+sink is two vertices joined by 4 parallel edges -> 4 spanning trees.
console.log('\n5. SANITY: known small values');
ok('1x1 (one cell, 4 edges to sink) -> 4 spanning trees', spanningTrees(1, 1) === 4n, `${spanningTrees(1,1)}`);
// 1x2: cells a-b, a has 3 sink edges, b has 3 sink edges, a-b one edge.
console.log(`     1x2 det = ${spanningTrees(1,2)}  (group of the two-cell sandpile)`);

console.log(`\n==== ${pass} passed, ${fail} failed ====`);
process.exit(fail ? 1 : 0);
