// verify-density.mjs — confirm the exact CEP local-density field against the sampler.
//
// The Arctic Circle Theorem gives the boundary; Cohn–Elkies–Propp (1996), Theorem 1,
// give the density of each of the four domino types at every interior point. This
// verifier does the one honest thing that settles it: it draws many uniformly-random
// tilings with the SAME sampler the page uses (arctic-core.mjs), measures the empirical
// fraction of each type in a grid of bins, and checks it against the CEP formula
// (cep-density.mjs) bin by bin. If the closed form is right and the mapping is right,
// measured ≈ predicted across the whole temperate zone to Monte-Carlo error — an
// "approaches a circle" upgraded to "matches an exact field, everywhere inside it."
//
// Run: node research/arctic-circle/verify-density.mjs
//
// The two modules under test are the page's own source of truth, imported verbatim.
import { sampleTiling, typeMap, diamondCells, inDiamond } from '../../public/strata/the-arctic-circle/arctic-core.mjs';
import { density, densities, P_north, inTemperate } from '../../public/strata/the-arctic-circle/cep-density.mjs';

// mulberry32, local copy (the sampler takes a rand()).
function mulberry32(seed) {
  let t = seed >>> 0;
  return function () {
    t += 0x6D2B79F5;
    let x = t;
    x = Math.imul(x ^ (x >>> 15), x | 1);
    x ^= x + Math.imul(x ^ (x >>> 7), x | 61);
    return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
  };
}

let passed = 0, failed = 0;
function ok(name, cond, detail = '') {
  if (cond) { passed++; console.log(`  ✓ ${name}${detail ? '  — ' + detail : ''}`); }
  else { failed++; console.log(`  ✗ ${name}  — ${detail}`); }
}

console.log('\nCEP LOCAL-DENSITY FIELD — exact facts (closed form)\n');

// (1) The four densities sum to 1 everywhere inside the disk (exact identity).
{
  const rand = mulberry32(1);
  let maxDev = 0;
  for (let i = 0; i < 20000; i++) {
    const x = rand() * 2 - 1, y = rand() * 2 - 1;
    if (!inTemperate(x, y)) continue;
    const s = densities(x, y).reduce((a, b) => a + b, 0);
    maxDev = Math.max(maxDev, Math.abs(s - 1));
  }
  ok('four densities sum to 1 across the disk', maxDev < 1e-12, `max |Σ−1| = ${maxDev.toExponential(2)}`);
}

// (2) At the exact centre, every type is 1/4 (the GIP middle-block result 1/4 + O(1/n)).
{
  const d = densities(0, 0);
  const allQuarter = d.every((v) => Math.abs(v - 0.25) < 1e-12);
  ok('centre density is 1/4 for all four types', allQuarter, `[${d.map((v) => v.toFixed(3)).join(', ')}]`);
}

// (3) The arctic circle is exactly the saturation locus: on the circle the field snaps
//     to 0 or 1. Approach the north pole radius from inside; P_north → 1. Approach any
//     non-cap boundary point; P_north → 0.
{
  let maxTop = 0, maxSide = 0;
  for (let t = 0; t < 200; t++) {
    const r = Math.sqrt(0.5) * (1 - 1e-6);
    // north cap: angle near +90°, y>1/2 region
    const thTop = Math.PI / 2 + (t / 200 - 0.5) * 0.4; // stay well inside the cap
    const xt = r * Math.cos(thTop), yt = r * Math.sin(thTop);
    if (yt > 0.5) maxTop = Math.max(maxTop, 1 - P_north(xt, yt));
    // a boundary point away from the north cap (bottom): should give ~0
    const thBot = -Math.PI / 2 + (t / 200 - 0.5) * 0.4;
    const xb = r * Math.cos(thBot), yb = r * Math.sin(thBot);
    if (yb < 0.5) maxSide = Math.max(maxSide, P_north(xb, yb));
  }
  ok('P_north → 1 on the north cap of the circle', maxTop < 0.02, `max(1−P) = ${maxTop.toFixed(4)}`);
  ok('P_north → 0 on the far arc of the circle', maxSide < 0.02, `max P = ${maxSide.toFixed(4)}`);
}

console.log('\nCEP FIELD vs THE SAMPLER — the empirical settlement\n');

// (4) THE MAIN CHECK. Sample many tilings, bin cells by normalized position, and compare
//     the measured type-fractions to the CEP field bin by bin, over the temperate zone.
function measureField(n, nSamples, seed0, binsPerUnit) {
  // Accumulator: for each bin, counts of each type and total.
  const acc = new Map(); // binKey -> {c:[4], tot, xs, ys}
  const bin = (v) => Math.round(v * binsPerUnit);
  for (let s = 0; s < nSamples; s++) {
    const rand = mulberry32(seed0 + s * 7919);
    const dominoes = sampleTiling(n, rand);
    const tm = typeMap(dominoes);
    for (const [a, b] of diamondCells(n)) {
      const x = (a + 0.5) / n, y = (b + 0.5) / n;
      if (x * x + y * y >= 0.5) continue;             // temperate zone only
      const t = tm.get(a + ',' + b);
      const bk = bin(x) + ':' + bin(y);
      let e = acc.get(bk);
      if (!e) { e = { c: [0, 0, 0, 0], tot: 0, sx: 0, sy: 0 }; acc.set(bk, e); }
      e.c[t]++; e.tot++; e.sx += x; e.sy += y;
    }
  }
  return acc;
}

function compareField(acc, minCount, guardR) {
  // For every well-sampled bin comfortably inside the circle, compare measured vs CEP.
  let worst = 0, sumSq = 0, nBins = 0, worstDesc = '';
  for (const e of acc.values()) {
    if (e.tot < minCount) continue;
    const x = e.sx / e.tot, y = e.sy / e.tot;
    if (x * x + y * y > 0.5 * guardR * guardR) continue; // stay off the sharp boundary
    for (let t = 0; t < 4; t++) {
      const meas = e.c[t] / e.tot;
      const pred = density(t, x, y);
      const d = Math.abs(meas - pred);
      if (d > worst) { worst = d; worstDesc = `type ${t} at (${x.toFixed(2)},${y.toFixed(2)}): meas ${meas.toFixed(3)} vs CEP ${pred.toFixed(3)}`; }
      sumSq += d * d; nBins++;
    }
  }
  return { worst, rms: Math.sqrt(sumSq / nBins), nBins, worstDesc };
}

// Moderately large n, enough samples that per-bin counts are in the hundreds.
{
  const n = 120, nSamples = 24, binsPerUnit = 12;
  console.log(`  sampling ${nSamples} tilings of order n=${n}, binning at ${binsPerUnit}/unit …`);
  const acc = measureField(n, nSamples, 12345, binsPerUnit);
  // guardR keeps bins strictly inside the circle (0.90 of arctic radius) so we test the
  // smooth interior, not the O(1/n)-wide boundary layer where finite-n blur dominates.
  const r = compareField(acc, 150, 0.90);
  console.log(`    ${r.nBins} (bin,type) comparisons; worst = ${r.worst.toFixed(3)}, rms = ${r.rms.toFixed(4)}`);
  console.log(`    worst bin: ${r.worstDesc}`);
  ok('CEP field matches the sampler across the interior (rms < 0.02)', r.rms < 0.02, `rms = ${r.rms.toFixed(4)}`);
  ok('no interior bin deviates more than 0.06', r.worst < 0.06, `worst = ${r.worst.toFixed(3)}`);
}

// (5) The mapping is UNIQUE: the identity type→CEP-type assignment beats all others.
//     If we had the reflection/rotation wrong, some permutation would fit far better.
{
  const n = 96, nSamples = 16, binsPerUnit = 10;
  const acc = measureField(n, nSamples, 999, binsPerUnit);
  // measured fractions and predicted fractions per bin
  const rows = [];
  for (const e of acc.values()) {
    if (e.tot < 150) continue;
    const x = e.sx / e.tot, y = e.sy / e.tot;
    if (x * x + y * y > 0.5 * 0.81) continue;
    rows.push({ meas: e.c.map((c) => c / e.tot), pred: densities(x, y) });
  }
  // all 24 permutations of the predicted-type labels; the identity must be best.
  const perms = permutations([0, 1, 2, 3]);
  let best = null, identityRms = null;
  for (const p of perms) {
    let ss = 0, cnt = 0;
    for (const row of rows) for (let t = 0; t < 4; t++) { const d = row.meas[t] - row.pred[p[t]]; ss += d * d; cnt++; }
    const rms = Math.sqrt(ss / cnt);
    if (p.join('') === '0123') identityRms = rms;
    if (!best || rms < best.rms) best = { p, rms };
  }
  ok('identity type-mapping is the unique best fit', best.p.join('') === '0123',
    `best perm ${best.p.join('')} (rms ${best.rms.toFixed(4)}); identity rms ${identityRms.toFixed(4)}`);
}

function permutations(arr) {
  if (arr.length <= 1) return [arr];
  const out = [];
  for (let i = 0; i < arr.length; i++) {
    const rest = arr.slice(0, i).concat(arr.slice(i + 1));
    for (const p of permutations(rest)) out.push([arr[i], ...p]);
  }
  return out;
}

console.log(`\n${failed === 0 ? '✓ ALL' : '✗'} ${passed}/${passed + failed} checks passed\n`);
process.exit(failed === 0 ? 0 : 1);
