#!/usr/bin/env node
// research/schelling/verify.mjs
//
// Ground truth for the stratum "A Third Is Enough" (Schelling's segregation
// model, with random relocation). The simulation lives in sim.mjs and has an
// equivalent port in the live page, so a named seed reproduces bit-for-bit. This file
// recomputes the headline and named-run figures and checks them, two ways:
//
//   • exact seeded runs — the reproducibility contract ("seed S, tau T → these
//     exact numbers"), so a reader can verify the live page against this file;
//   • deterministic ensembles over seeds 1..40 — the headline statistics
//     (the micro→macro gap, sampled rise, endpoints at the cap, grid size and vacancy).
//
// Everything is deterministic: no Math.random, only the seeded mulberry32 in
// sim.mjs. Run:  node research/schelling/verify.mjs

'use strict';
import { run, makeGrid, likeFraction, unhappyCount, mulberry32 } from './sim.mjs';

let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, cond, got, want) {
  if (cond) { pass++; console.log(`  ✓ ${name}` + (got !== undefined ? `  (${got})` : '')); }
  else { fail++; console.log(`  ✗ ${name}  — got ${got}, want ${want}`); }
}
// mean of run(...) field over seeds 1..K (deterministic)
function ensemble(L, v, tau, field, K = 40, maxRounds = 400) {
  let s = 0, settled = 0;
  for (let seed = 1; seed <= K; seed++) {
    const o = run(L, v, tau, seed, maxRounds);
    s += o[field];
    if (o.finalUnhappy === 0) settled++;
  }
  return { mean: s / K, settleRate: settled / K };
}

console.log('\nSchelling verifier — mild preference, hard borders\n');

// [1] The reproducibility contract: exact numbers for named seeds. These are the
//     runs the page invites the reader to reproduce live in the browser.
console.log('[1] exact seeded runs (the page’s "reproduce this" contract):');
{
  const o = run(50, 0.10, 0.30, 12345, 300);
  check('seed 12345, τ=0.30, 50×0.10 → start likeFrac',
    approx(o.startLike, 0.5010, 5e-4), o.startLike.toFixed(4), 0.5010);
  check('...→ end likeFrac', approx(o.endLike, 0.7638, 5e-4), o.endLike.toFixed(4), 0.7638);
  check('...→ rounds to settle', o.rounds === 18, o.rounds, 18);
  check('...→ everyone content at the end (0 unhappy)', o.finalUnhappy === 0, o.finalUnhappy, 0);
}
{
  const o = run(50, 0.10, 1 / 3, 7, 300);
  check('seed 7, τ=1/3 → settles with 0 unhappy', o.finalUnhappy === 0, o.finalUnhappy, 0);
  check('seed 7, τ=1/3 → end likeFrac ≈ 0.76', approx(o.endLike, 0.76, 0.05), o.endLike.toFixed(4), '~0.76');
}

// [2] The starting grid really is ~perfectly mixed (no hidden head start).
console.log('\n[2] the initial grid is genuinely mixed (~0.50), not pre-sorted:');
{
  const e = ensemble(50, 0.10, 1 / 3, 'startLike').mean;
  check('mean start like-fraction over 40 seeds ≈ 0.50', approx(e, 0.4994, 2e-3), e.toFixed(4), 0.4994);
}

// [3] THE HEADLINE: a preference for 1/3 produces ~3/4 same-type neighbours,
//     and every agent ends content. Preference 0.33 → outcome 0.76.
console.log('\n[3] the paradox, measured — τ=1/3 → end ≈ 0.76, all content:');
{
  const end = ensemble(50, 0.10, 1 / 3, 'endLike');
  const uh = ensemble(50, 0.10, 1 / 3, 'finalUnhappy');
  check('mean end like-fraction ≈ 0.757', approx(end.mean, 0.7568, 3e-3), end.mean.toFixed(4), 0.7568);
  check('the micro→macro gap is real: outcome (≈0.76) ≫ preference (0.33)', end.mean - 1 / 3 > 0.4, (end.mean - 1 / 3).toFixed(3), '> 0.40');
  check('every run settles with 0 unhappy (contentment coexists with segregation)', uh.mean === 0 && end.settleRate === 1, `unhappy ${uh.mean}, settle ${end.settleRate}`, '0 / 1.0');
}

// [4] Sampled rise: mean segregation is non-decreasing at these seven
//     thresholds, reaching near-total segregation by tau 0.75.
console.log('\n[4] mean segregation is non-decreasing at the seven tested thresholds:');
{
  const taus = [0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.75];
  const vals = taus.map((t) => ensemble(50, 0.10, t, 'endLike').mean);
  let mono = true; for (let i = 1; i < vals.length; i++) if (vals[i] < vals[i - 1] - 1e-6) mono = false;
  check('mean end like-fraction is non-decreasing at seven τ values from 0.20 to 0.75', mono, vals.map((v) => v.toFixed(3)).join(' '), 'non-decreasing');
  check('near-total segregation by τ=0.75 (≈ 0.999)', approx(vals[vals.length - 1], 0.999, 3e-3), vals[vals.length - 1].toFixed(4), 0.999);
}

// [5] Finite-cap endpoints: these random-start runs settle at tau 0.75,
//     but none at tau 0.76 settles within 400 rounds. This does not exclude
//     equilibria or establish infinite churn. Check the local threshold separately.
console.log('\n[5] measured endpoints after settling or 400 rounds:');
{
  const lo = ensemble(50, 0.10, 0.75, 'endLike', 40);  // 6/8 meets the local threshold
  const hi = ensemble(50, 0.10, 0.76, 'endLike', 40);  // now needs 7/8
  check('τ=0.75: all 40 seeds settle within 400 rounds, mean ≈ 0.999', lo.settleRate === 1 && lo.mean > 0.99, `settle ${lo.settleRate}, like ${lo.mean.toFixed(3)}`, 'settles, ~0.999');
  check('τ=0.76: 0/40 seeds settle within 400 rounds, mean endpoint ≈ 0.51', hi.settleRate === 0 && hi.mean < 0.6, `settle ${hi.settleRate}, like ${hi.mean.toFixed(3)}`, 'unsettled at 400 rounds, ~0.51');
}
// The local integer threshold follows directly from the happiness rule.
console.log('    (local arithmetic, not a proof of the global outcome:)');
{
  // an agent with 8 same-typed-or-not neighbours: happy iff same/8 >= tau.
  // Build a tiny hand-made neighbourhood: 6 same, 2 other, of a full ring of 8.
  function happyWith(same, occ, tau) { return same / occ >= tau; }
  check('6 of 8 same is content at τ=0.75 but NOT at τ=0.76',
    happyWith(6, 8, 0.75) && !happyWith(6, 8, 0.76), '6/8: ok@.75, no@.76', '6/8 meets 0.75 but not 0.76');
  check('at τ=0.76, 7 of 8 same is sufficient and 6 of 8 is not',
    happyWith(7, 8, 0.76) && !happyWith(6, 8, 0.76), '7/8 = 0.875', '≥ 0.76');
}

// [6] Robustness: the ~0.76 outcome at τ=1/3 barely moves with grid size or
//     vacancy — it is the mechanism, not a tuned instance.
console.log('\n[6] robustness — τ=1/3 gives ≈ 0.75–0.76 across grid size and vacancy:');
{
  for (const [L, v] of [[30, 0.10], [50, 0.10], [80, 0.10], [50, 0.05], [50, 0.20], [50, 0.30]]) {
    const m = ensemble(L, v, 1 / 3, 'endLike').mean;
    check(`L=${L}, vacancy=${v} → end ≈ 0.75–0.76`, m > 0.74 && m < 0.77, m.toFixed(4), '0.75–0.76');
  }
}

// [7] Sanity: the PRNG and the metric agree with independent recomputation on a
//     tiny hand-checkable grid.
console.log('\n[7] metric sanity on a hand-checkable configuration:');
{
  // a 3x3 fully A grid (no empties): every occupied agent's neighbours are all
  // same → like-fraction must be exactly 1.
  const cells = Int8Array.from([1, 1, 1, 1, 1, 1, 1, 1, 1]);
  check('all-A 3×3 → like-fraction = 1', likeFraction(cells, 3) === 1, likeFraction(cells, 3), 1);
  // a checkerboard of A/B → every agent's occupied neighbours: the 4 edge-
  // adjacent are the other type, the 4 diagonal are same. On a 4x4 checkerboard
  // the interior agents see 4 same (diagonals) of 8 → 0.5; edges differ. Just
  // assert it is strictly below the all-same case and above 0.
  const cb = new Int8Array(16); for (let i = 0; i < 16; i++) { const x = i % 4, y = (i / 4) | 0; cb[i] = ((x + y) % 2) + 1; }
  const lf = likeFraction(cb, 4);
  check('checkerboard like-fraction is anti-clustered (< 0.5)', lf < 0.5, lf.toFixed(4), '< 0.5');
}

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