// verify.mjs — prove the facts the instrument "Sandpiles, as percussion" makes
// audible, from scratch, against engine.mjs. Run: node research/sandpiles/verify.mjs
//
// What is checked:
//   1. ABELIAN PROPERTY (the load-bearing truth) — the stable configuration AND
//      the full odometer (per-site topple counts) are identical no matter the
//      order in which unstable sites are toppled: parallel waves vs row-major
//      sequential vs many uniformly-random orders. This is Dhar's theorem; the
//      instrument's honesty rests on it (the rhythm you hear is order-free).
//   2. The total avalanche size = sum of the odometer, order-independent.
//   3. The IDENTITY element e of the sandpile group: stable, idempotent (e⊕e=e),
//      and acts as the identity on the maximal recurrent configuration.
//   4. SELF-ORGANIZED CRITICALITY — driving the pile to its stationary state and
//      recording avalanche sizes gives a heavy-tailed (power-law-like)
//      distribution spanning orders of magnitude with no characteristic scale.
//   5. Landmark single avalanches the page exposes as presets are reproduced
//      exactly (the "one grain that topples the whole quadrant").

import { make, clone, eq, stabilize, add, identity, drive, centerDrop, randomDrop, THRESH } from './engine.mjs';

let fails = 0, n = 0;
const ok = (c, m) => { n++; if (!c) { fails++; console.log('  ✗ ' + m); } else console.log('  ✓ ' + m); };
// a small deterministic PRNG so the run is reproducible
function mulberry32(a) { return function () { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }

function odoEq(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; }

console.log('\n1. THE ABELIAN PROPERTY — final state + odometer are order-independent');
{
  const rng = mulberry32(12345);
  let worstCheck = 0;
  for (let trial = 0; trial < 200; trial++) {
    const N = 3 + ((rng() * 6) | 0);            // 3..8
    // a random unstable configuration: heights 0..7
    const base = make(N, 0);
    for (let i = 0; i < base.h.length; i++) base.h[i] = (rng() * 8) | 0;

    const gWave = clone(base); const rWave = stabilize(gWave, 'wave');
    const gSeq = clone(base);  const rSeq = stabilize(gSeq, 'seq');
    const same = eq(gWave, gSeq) && odoEq(rWave.odometer, rSeq.odometer) && rWave.topples === rSeq.topples;
    if (!same) { console.log(`    mismatch wave vs seq at trial ${trial}, N=${N}`); worstCheck = 1; break; }

    // and several independent random toppling orders
    for (let s = 0; s < 4; s++) {
      const gRand = clone(base); const rRand = stabilize(gRand, 'random', mulberry32(1000 + trial * 13 + s));
      if (!eq(gWave, gRand) || !odoEq(rWave.odometer, rRand.odometer) || rWave.topples !== rRand.topples) {
        console.log(`    mismatch wave vs random at trial ${trial}, N=${N}, seed ${s}`); worstCheck = 1; break;
      }
    }
    if (worstCheck) break;
  }
  ok(worstCheck === 0, '200 random configs (N=3..8): wave ≡ row-major ≡ 4 random orders — identical final grid, odometer, and total topples');
}

console.log('\n2. AVALANCHE SIZE = sum of odometer, and the abelian add is well-defined');
{
  const N = 6;
  const g = make(N, 3);            // maximal stable
  const before = clone(g);
  g.h[centerDrop(N)]++;            // one grain at the centre tips it
  const res = stabilize(g, 'wave');
  let odoSum = 0; for (const v of res.odometer) odoSum += v;
  ok(odoSum === res.topples, `avalanche size = Σ odometer (${res.topples} topplings over ${res.waves} waves)`);
  // ⊕ is commutative on this pile (abelian): a⊕b == b⊕a
  const a = make(N, 0), b = make(N, 0);
  for (let i = 0; i < a.h.length; i++) { a.h[i] = 2; b.h[i] = 1; }
  ok(eq(add(a, b), add(b, a)), 'a ⊕ b = b ⊕ a (the group is abelian)');
}

console.log('\n3. THE IDENTITY ELEMENT of the sandpile group');
for (const N of [4, 6, 8, 12]) {
  const e = identity(N);
  let stable = true; for (const v of e.h) if (v >= THRESH || v < 0) stable = false;
  const idem = eq(add(e, e), e);                       // e ⊕ e = e
  const cmax = make(N, THRESH - 1);                    // all 3's — the maximal stable config (recurrent)
  const actsId = eq(add(e, cmax), cmax);               // e ⊕ c_max = c_max
  let nonTrivial = false; for (const v of e.h) if (v !== THRESH - 1) nonTrivial = true;
  ok(stable && idem && actsId, `N=${N}: identity is stable, idempotent (e⊕e=e), and fixes the maximal recurrent config (e⊕c_max=c_max)${nonTrivial ? '' : ' — note: trivial'}`);
}
{
  // the identity is genuinely non-trivial (the famous fractal) for N≥4
  const e = identity(16); let distinct = new Set(e.h);
  ok(distinct.size >= 3, `the 16×16 identity is the non-trivial fractal (heights present: {${[...distinct].sort().join(',')}})`);
}

console.log('\n4. SELF-ORGANIZED CRITICALITY — avalanche sizes are heavy-tailed');
{
  const N = 40;
  // burn in to the stationary (recurrent) state, then sample
  const warm = drive(N, 6000, randomDrop, mulberry32(7), null);
  const run = drive(N, 30000, randomDrop, mulberry32(99), warm.final);
  const sizes = run.sizes.filter(s => s > 0);          // non-trivial avalanches
  const maxS = Math.max(...sizes), meanS = sizes.reduce((a, b) => a + b, 0) / sizes.length;
  const variance = sizes.reduce((a, b) => a + (b - meanS) * (b - meanS), 0) / sizes.length;
  const cv = Math.sqrt(variance) / meanS;              // coefficient of variation
  // SOC signature: huge relative fluctuations (cv ≫ 1) and a span of many orders
  // of magnitude — the distribution has no characteristic scale.
  ok(cv > 1.5 && maxS > 1000 && maxS > 15 * meanS,
     `avalanche sizes have no characteristic scale: max ${maxS}, mean ${meanS.toFixed(1)}, std/mean = ${cv.toFixed(2)} (≫1)`);

  // a crude power-law check: in a true scale-free regime, the number of avalanches
  // of size ≥ s falls roughly as a straight line in log–log. Fit the survival
  // function over the scaling window and confirm a negative slope near the ASM range.
  const sorted = [...sizes].sort((a, b) => a - b);
  const survAt = (s) => sorted.length - lowerBound(sorted, s);
  const xs = [], ys = [];
  for (let s = 4; s <= maxS / 4; s *= 2) {
    const c = survAt(s); if (c < 20) break;
    xs.push(Math.log(s)); ys.push(Math.log(c));
  }
  const slope = linfit(xs, ys);
  ok(xs.length >= 4 && slope < -0.3 && slope > -2.0, `log–log survival slope = ${slope.toFixed(3)} over ${xs.length} octaves — power-law-like (ASM size exponent τ−1 ≈ −0.2..−0.5 is subtle/debated; this is descriptive)`);
}

console.log('\n5. LANDMARK AVALANCHE — one grain onto a flat-3 pile, reproduced exactly');
{
  const N = 7;
  const g = make(N, 3);
  g.h[centerDrop(N)]++;            // 4 at the centre
  const res = stabilize(g, 'wave');
  // recompute the total a second way: full re-stabilize from the same start, seq order
  const g2 = make(N, 3); g2.h[centerDrop(N)]++; const res2 = stabilize(g2, 'seq');
  ok(res.topples === res2.topples && eq(g, g2), `centre grain on flat-3 (N=7): ${res.topples} topplings, ${res.waves} waves — identical under wave and sequential relaxation`);
}

// helpers
function lowerBound(arr, x) { let lo = 0, hi = arr.length; while (lo < hi) { const m = (lo + hi) >> 1; if (arr[m] < x) lo = m + 1; else hi = m; } return lo; }
function linfit(xs, ys) { const n = xs.length; let sx = 0, sy = 0, sxx = 0, sxy = 0; for (let i = 0; i < n; i++) { sx += xs[i]; sy += ys[i]; sxx += xs[i] * xs[i]; sxy += xs[i] * ys[i]; } return (n * sxy - sx * sy) / (n * sxx - sx * sx); }

console.log(`\n${fails === 0 ? 'ALL ' + n + ' CHECKS PASSED' : fails + ' / ' + n + ' CHECKS FAILED'}`);
process.exit(fails === 0 ? 0 : 1);
