// verify.mjs — the checks behind /strata/the-arctic-circle/.
//
// Runs the SAME sampler the page runs (public/strata/the-arctic-circle/arctic-core.mjs —
// one source of truth) and confronts it with four kinds of claim:
//
//   EXACT (proved by independent brute force / arithmetic):
//     · the order-n Aztec diamond has exactly 2^(n(n+1)/2) domino tilings  [EKLP 1992]
//     · domino-shuffling draws them UNIFORMLY (every tiling equally likely) [JPS 1998]
//   STRUCTURAL:
//     · each of the four frozen corners is one single domino type; the centre mixes all four
//   ASYMPTOTIC (a limit theorem — demonstrated by seeded Monte-Carlo approaching the limit,
//   never claimed as an exact finite-n equality):
//     · the frozen/temperate boundary is a CIRCLE of radius n/√2                [JPS 1998]
//     · the frozen area fraction → 1 − π/4 ≈ 0.2146 as n → ∞
//
// Sources: W. Jockusch, J. Propp, P. Shor, "Random Domino Tilings and the Arctic Circle
// Theorem," arXiv:math/9801068 (1998). N. Elkies, G. Kuperberg, M. Larsen, J. Propp,
// "Alternating-Sign Matrices and Domino Tilings I–II," J. Algebraic Combin. 1 (1992),
// 111–132 & 219–234. J. Propp, "Generalized domino-shuffling," Theoret. Comput. Sci. 303
// (2003) 267–301. H. Cohn, N. Elkies, J. Propp, "Local statistics for random domino tilings
// of the Aztec diamond," Duke Math. J. 85 (1996) 117–166.
//
// Run: node research/arctic-circle/verify.mjs

import {
  sampleTiling, mulberry32, isValidTiling, tilingKey, dominoType,
  inDiamond, diamondCells, frozenFraction,
} from '../../public/strata/the-arctic-circle/arctic-core.mjs';

let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) { pass++; console.log('  \x1b[32m✓\x1b[0m ' + msg); } else { fail++; console.log('  \x1b[31m✗\x1b[0m ' + msg); } };
const H = (s) => console.log('\n\x1b[1m' + s + '\x1b[0m');

// ────────────────────────────────────────────────────────────────────────────
// 1. EXACT COUNT — independent exhaustive enumeration vs 2^(n(n+1)/2).
// This enumerator shares no code with the sampler: it fills the first free cell with a
// horizontal or vertical domino and backtracks, counting complete tilings.
// ────────────────────────────────────────────────────────────────────────────
function enumerateCount(n) {
  const present = new Set();
  const list = [];
  for (let b = -n; b <= n - 1; b++)
    for (let a = -n; a <= n - 1; a++)
      if (inDiamond(a, b, n)) { present.add(a + ',' + b); list.push([a, b]); }
  const covered = new Set();
  let count = 0;
  function firstFree() { for (const [a, b] of list) if (!covered.has(a + ',' + b)) return [a, b]; return null; }
  function rec(remaining) {
    if (remaining === 0) { count++; return; }
    const f = firstFree(); if (!f) return;
    const [a, b] = f, k = a + ',' + b;
    const kr = (a + 1) + ',' + b;                       // horizontal
    if (present.has(kr) && !covered.has(kr)) { covered.add(k); covered.add(kr); rec(remaining - 2); covered.delete(k); covered.delete(kr); }
    const kd = a + ',' + (b + 1);                        // vertical
    if (present.has(kd) && !covered.has(kd)) { covered.add(k); covered.add(kd); rec(remaining - 2); covered.delete(k); covered.delete(kd); }
  }
  rec(list.length);
  return count;
}

H('1. Exact tiling count — brute-force enumeration vs 2^(n(n+1)/2)  [EKLP 1992]');
for (let n = 1; n <= 6; n++) {
  const got = enumerateCount(n);
  const exp = 2 ** ((n * (n + 1)) / 2);
  ok(got === exp, `order ${n}: ${got} tilings  =  2^${(n * (n + 1)) / 2} = ${exp}`);
}

// ────────────────────────────────────────────────────────────────────────────
// 2. SAMPLER VALIDITY — every drawn tiling legally covers the diamond.
// ────────────────────────────────────────────────────────────────────────────
H('2. Domino-shuffling produces legal tilings of the diamond');
{
  const rand = mulberry32(20260701);
  for (const n of [1, 2, 3, 5, 10, 25, 60]) {
    let allValid = true;
    for (let t = 0; t < 30; t++) if (!isValidTiling(sampleTiling(n, rand), n)) { allValid = false; break; }
    ok(allValid, `order ${n}: 30/30 samples cover every cell exactly once, inside the diamond`);
  }
}

// ────────────────────────────────────────────────────────────────────────────
// 3. UNIFORMITY — chi-square over the full tiling set (n=1,2,3). The whole point of the
// shuffle is that every one of the 2^(n(n+1)/2) tilings is equally likely.
// ────────────────────────────────────────────────────────────────────────────
H('3. Uniformity of the sampler — chi-square over all tilings  [JPS 1998]');
function uniformity(n, samples, seed, chiCrit) {
  const rng = mulberry32(seed);
  const counts = new Map();
  for (let i = 0; i < samples; i++) { const k = tilingKey(sampleTiling(n, rng)); counts.set(k, (counts.get(k) || 0) + 1); }
  const expected = 2 ** ((n * (n + 1)) / 2);
  const exp = samples / expected;
  let chi = 0;
  for (const c of counts.values()) chi += (c - exp) * (c - exp) / exp;
  chi += (expected - counts.size) * exp;      // tilings never seen
  ok(counts.size === expected && chi < chiCrit,
    `order ${n}: all ${expected} tilings seen; χ²=${chi.toFixed(1)} < ${chiCrit} (df=${expected - 1}), samples=${samples}`);
}
uniformity(1, 40000, 101, 10.83);     // df 1,  p=0.001 critical 10.83
uniformity(2, 120000, 202, 24.32);    // df 7,  p=0.001 critical 24.32
uniformity(3, 160000, 303, 103.4);    // df 63, p=0.001 critical ≈103.4

// ────────────────────────────────────────────────────────────────────────────
// 4. FROZEN-CORNER STRUCTURE — each corner is a single type; the centre holds all four.
// This is the mechanism that makes the circle visible: four solid-colour corners.
// ────────────────────────────────────────────────────────────────────────────
H('4. The four frozen corners are each one domino type; the centre mixes all four');
{
  const rng = mulberry32(555);
  const n = 80, M = 8;
  // corner tallies deep in each tip; centre type set near the origin
  const cornerTypes = [new Set(), new Set(), new Set(), new Set()]; // top,bottom,right,left
  const centreTypes = new Set();
  for (let s = 0; s < M; s++) {
    const dom = sampleTiling(n, rng);
    for (const d of dom) {
      const t = dominoType(d);
      const a = d.a, b = d.b;
      if (b > n * 0.82) cornerTypes[0].add(t);        // top
      else if (b < -n * 0.82) cornerTypes[1].add(t);  // bottom
      else if (a > n * 0.82) cornerTypes[2].add(t);   // right
      else if (a < -n * 0.82) cornerTypes[3].add(t);  // left
      if (Math.abs(a) < n * 0.06 && Math.abs(b) < n * 0.06) centreTypes.add(t);
    }
  }
  const names = ['top→H↑(0)', 'bottom→H↓(1)', 'right→V→(2)', 'left→V←(3)'];
  const wanted = [0, 1, 2, 3];
  for (let i = 0; i < 4; i++)
    ok(cornerTypes[i].size === 1 && cornerTypes[i].has(wanted[i]),
      `${names[i]}: deep corner is exactly one type {${[...cornerTypes[i]].join(',')}}`);
  ok(centreTypes.size === 4, `centre (temperate zone) contains all four types {${[...centreTypes].sort().join(',')}}`);
}

// ────────────────────────────────────────────────────────────────────────────
// 5. THE ARCTIC CIRCLE — the frozen/temperate boundary is a circle of radius n/√2.
// Ensemble: P(cell = its corner's type) saturates to 1 inside the frozen corner and the
// saturation edge traces the circle. We read the edge along each axis (τ=0.9), fit a
// radius (centre fixed at the diamond centre) and report the RMS deviation. The finite-n
// transition zone has width ~n^{1/3}, so R/n sits a hair off 1/√2 and the fit tightens
// (rms/n shrinks) as n grows — the honest signature of an asymptotic law.
// ────────────────────────────────────────────────────────────────────────────
H('5. The boundary is a CIRCLE of radius n/√2 (≈0.7071·n)  [JPS 1998]');
function circleFit(n, M, seed, tau) {
  const rng = mulberry32(seed);
  const P = new Map();
  for (let s = 0; s < M; s++) {
    const dom = sampleTiling(n, rng);
    for (const d of dom) {
      const t = dominoType(d);
      const cc = d.o === 'H' ? [[d.a, d.b], [d.a + 1, d.b]] : [[d.a, d.b], [d.a, d.b + 1]];
      for (const [a, b] of cc) { const k = a + ',' + b; let e = P.get(k); if (!e) { e = [0, 0, 0, 0, 0]; P.set(k, e); } e[t]++; e[4]++; }
    }
  }
  const prob = (a, b, t) => { const e = P.get(a + ',' + b); return e && e[4] ? e[t] / e[4] : null; };
  const pts = [];
  // scan inward from each tip; keep the first saturation-edge point, restricted to the
  // ±45° sector around that corner's axis so each point sits on that corner's arc.
  for (let a = -n; a <= n - 1; a++) for (let b = n - 1; b >= -n; b--) { if (!inDiamond(a, b, n)) continue; const p = prob(a, b, 0); if (p === null) continue; if (p < tau) { const x = a + 0.5, y = b + 0.5; if (Math.abs(x) <= Math.abs(y)) pts.push([x, y]); break; } }
  for (let a = -n; a <= n - 1; a++) for (let b = -n; b <= n - 1; b++) { if (!inDiamond(a, b, n)) continue; const p = prob(a, b, 1); if (p === null) continue; if (p < tau) { const x = a + 0.5, y = b + 0.5; if (Math.abs(x) <= Math.abs(y)) pts.push([x, y]); break; } }
  for (let b = -n; b <= n - 1; b++) for (let a = n - 1; a >= -n; a--) { if (!inDiamond(a, b, n)) continue; const p = prob(a, b, 2); if (p === null) continue; if (p < tau) { const x = a + 0.5, y = b + 0.5; if (Math.abs(y) <= Math.abs(x)) pts.push([x, y]); break; } }
  for (let b = -n; b <= n - 1; b++) for (let a = -n; a <= n - 1; a++) { if (!inDiamond(a, b, n)) continue; const p = prob(a, b, 3); if (p === null) continue; if (p < tau) { const x = a + 0.5, y = b + 0.5; if (Math.abs(y) <= Math.abs(x)) pts.push([x, y]); break; } }
  let sr = 0, sr2 = 0;
  for (const [x, y] of pts) { const r = Math.hypot(x, y); sr += r; sr2 += r * r; }
  const R = sr / pts.length, rms = Math.sqrt(Math.max(0, sr2 / pts.length - R * R));
  return { Rn: R / n, rmsn: rms / n, K: pts.length };
}
{
  const target = 1 / Math.SQRT2;
  const rows = [];
  let lastRms = 1;
  let rmsShrinks = true;
  for (const [n, M] of [[40, 40], [64, 40], [96, 32]]) {
    const f = circleFit(n, M, 7000 + n, 0.9);
    rows.push([n, f]);
    ok(Math.abs(f.Rn - target) < 0.03, `n=${n}: fitted R/n=${f.Rn.toFixed(4)}  (target 1/√2=${target.toFixed(4)}, |Δ|<0.03)`);
    ok(f.rmsn < 0.02, `n=${n}: boundary is circular — rms/n=${f.rmsn.toFixed(4)} < 0.02 (${f.K} boundary points)`);
    if (f.rmsn > lastRms + 0.004) rmsShrinks = false;
    lastRms = f.rmsn;
  }
  ok(rmsShrinks, `the circle sharpens with n: rms/n non-increasing (${rows.map(([n, f]) => n + ':' + f.rmsn.toFixed(3)).join(' → ')})`);
}

// ────────────────────────────────────────────────────────────────────────────
// 6. THE FROZEN AREA FRACTION → 1 − π/4. A finite-n estimator (contiguous corner runs)
// over-counts and so descends toward 0.2146 from above as n grows — reported as a trend.
// ────────────────────────────────────────────────────────────────────────────
H('6. Frozen area fraction descends toward 1 − π/4 ≈ 0.2146 as n grows');
{
  const target = 1 - Math.PI / 4;
  const rng = mulberry32(99);
  const ns = [30, 60, 120];
  const fr = [];
  for (const n of ns) {
    let s = 0, K = 5;
    for (let i = 0; i < K; i++) s += frozenFraction(sampleTiling(n, rng), n);
    fr.push(s / K);
  }
  ok(fr[0] > fr[1] && fr[1] > fr[2],
    `monotone descent: ${ns.map((n, i) => `n=${n}:${fr[i].toFixed(4)}`).join('  >  ')}`);
  ok(fr[fr.length - 1] > target && fr[fr.length - 1] - target < 0.09,
    `largest n stays above and near the limit: ${fr[fr.length - 1].toFixed(4)} → 1−π/4=${target.toFixed(4)}`);
}

// ────────────────────────────────────────────────────────────────────────────
console.log(`\n${'─'.repeat(64)}`);
console.log(fail === 0
  ? `\x1b[32m✓ all ${pass} checks pass\x1b[0m`
  : `\x1b[31m✗ ${fail} of ${pass + fail} checks FAILED\x1b[0m`);
process.exit(fail === 0 ? 0 : 1);
