#!/usr/bin/env node
// verify.mjs — the machine check behind /strata/the-myth-of-barter/
//
// The page makes ONE quantitative claim, Jevons' point made operable:
//   In a village where everyone produces one good and wants another,
//   a *barter* trade needs a DOUBLE COINCIDENCE of wants (rare), while a
//   *credit ledger* only needs the wanted good to exist somewhere (common).
//
// We assert two exact closed forms and confirm each against a seeded
// Monte-Carlo of the actual village. Model (stated on the page):
//   - n agents, g good-types (g >= 2).
//   - agent i PRODUCES good P_i ~ Uniform{0..g-1}.
//   - agent i WANTS  good W_i ~ Uniform over the g-1 types != P_i
//     (nobody wants what they already make).
//
// BARTER measure  B(n,g) = expected fraction of agents who have AT LEAST ONE
//   possible barter partner — i.e. some j with P_j=W_i AND W_j=P_i (a double
//   coincidence). This is the GENEROUS upper bound on barter: it counts an
//   agent as "served" merely for being *able* to trade, before any matching
//   contention (one unit each) thins it further. Even so it is small.
//     Closed form: q = (1/g)*(1/(g-1)) = P(a specific ordered pair is a
//     double coincidence); B = 1 - (1-q)^(n-1).
//   Derivation of q: P(P_j = W_i) = 1/g. Given that, W_j is uniform on the
//   g-1 goods != P_j (= != W_i); P_i is among them because P_i != W_i, so
//   P(W_j = P_i | P_j = W_i) = 1/(g-1). The (n-1) partner-trials are
//   independent given agent i's own (P_i, W_i), so the product form is exact.
//
// CREDIT measure  C(n,g) = expected fraction of agents whose wanted good is
//   PRODUCED BY SOMEONE ELSE (so a chain of IOUs can deliver it; the ledger,
//   not a coincidence, closes the loop).
//     Closed form: C = 1 - (1 - 1/g)^(n-1).
//   (P(a specific other produces W_i) = 1/g, independent across the n-1.)
//
// Both forms are exact in EXPECTATION; the Monte-Carlo confirms them.
// Run: node research/the-myth-of-barter/verify.mjs

'use strict';

// ---- deterministic RNG (mulberry32) so the check 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 closedForms(n, g) {
  const q = (1 / g) * (1 / (g - 1));
  const barter = 1 - Math.pow(1 - q, n - 1);
  const credit = 1 - Math.pow(1 - 1 / g, n - 1);
  return { q, barter, credit };
}

// One village; returns {barterServed, creditServed} as fractions in [0,1].
function village(n, g, rng) {
  const P = new Int32Array(n);
  const W = new Int32Array(n);
  for (let i = 0; i < n; i++) {
    P[i] = Math.floor(rng() * g);
    let w = Math.floor(rng() * (g - 1)); // pick among g-1 others
    if (w >= P[i]) w++;                  // skip own good -> uniform on != P[i]
    W[i] = w;
  }
  // produced[g]: how many agents make each good (for the credit measure)
  const produced = new Int32Array(g);
  for (let i = 0; i < n; i++) produced[P[i]]++;

  let barterServed = 0, creditServed = 0;
  for (let i = 0; i < n; i++) {
    // CREDIT: does anyone ELSE produce W_i? (subtract self iff i produces W_i,
    // but i never produces W_i since W_i != P_i, so produced[W_i] counts others)
    if (produced[W[i]] > 0) creditServed++;
    // BARTER: exists j != i with P_j == W_i and W_j == P_i ?
    for (let j = 0; j < n; j++) {
      if (j === i) continue;
      if (P[j] === W[i] && W[j] === P[i]) { barterServed++; break; }
    }
  }
  return { barter: barterServed / n, credit: creditServed / n };
}

function monteCarlo(n, g, trials, seed) {
  const rng = mulberry32(seed);
  let sb = 0, sc = 0;
  for (let t = 0; t < trials; t++) {
    const r = village(n, g, rng);
    sb += r.barter; sc += r.credit;
  }
  return { barter: sb / trials, credit: sc / trials };
}

// ---- the checks ----
let pass = 0, fail = 0;
const log = (ok, msg) => { console.log((ok ? 'ok  ' : 'FAIL') + ' ' + msg); ok ? pass++ : fail++; };

console.log('THE MYTH OF BARTER — verifier\n');
console.log('Claim: barter needs a double coincidence (rare); credit needs only');
console.log('that the wanted good exist somewhere (common). Closed form vs Monte-Carlo.\n');

const cases = [
  { n: 50, g: 20 },
  { n: 100, g: 25 },
  { n: 30, g: 10 },
  { n: 200, g: 40 },
  { n: 25, g: 5 },
];
const TRIALS = 4000;
for (let c = 0; c < cases.length; c++) {
  const { n, g } = cases[c];
  const cf = closedForms(n, g);
  const mc = monteCarlo(n, g, TRIALS, 12345 + c * 1000);
  const tol = 0.02; // 4000 trials -> well within 2%
  console.log(`\nn=${n}, g=${g}:`);
  console.log(`  q (one pair is a double coincidence) = 1/(g(g-1)) = 1/${g * (g - 1)} = ${cf.q.toExponential(3)}`);
  console.log(`  barter served: closed ${(cf.barter * 100).toFixed(2)}%  vs  MC ${(mc.barter * 100).toFixed(2)}%`);
  console.log(`  credit served: closed ${(cf.credit * 100).toFixed(2)}%  vs  MC ${(mc.credit * 100).toFixed(2)}%`);
  log(Math.abs(cf.barter - mc.barter) < tol, `barter closed form matches Monte-Carlo (|Δ|<${tol}) [n=${n},g=${g}]`);
  log(Math.abs(cf.credit - mc.credit) < tol, `credit closed form matches Monte-Carlo (|Δ|<${tol}) [n=${n},g=${g}]`);
  log(cf.credit > cf.barter, `credit beats barter [n=${n},g=${g}]: ${(cf.credit * 100).toFixed(0)}% vs ${(cf.barter * 100).toFixed(0)}%`);
}

// Jevons' exact pair probability, sanity-checked at small g by full enumeration.
function enumeratePairProb(g) {
  // Two agents A,B; P,W each uniform with W!=P. Count ordered (Pa,Wa,Pb,Wb)
  // with the double-coincidence Pb=Wa && Wb=Pa, over all valid assignments.
  let good = 0, total = 0;
  for (let Pa = 0; Pa < g; Pa++) for (let Wa = 0; Wa < g; Wa++) {
    if (Wa === Pa) continue;
    for (let Pb = 0; Pb < g; Pb++) for (let Wb = 0; Wb < g; Wb++) {
      if (Wb === Pb) continue;
      total++;
      if (Pb === Wa && Wb === Pa) good++;
    }
  }
  return good / total;
}
console.log('\nJevons pair probability q = 1/(g(g-1)), checked by full enumeration:');
for (const g of [3, 4, 5, 8]) {
  const enum_ = enumeratePairProb(g);
  const form = 1 / (g * (g - 1));
  console.log(`  g=${g}: enumerated ${enum_.toExponential(4)}  formula ${form.toExponential(4)}`);
  log(Math.abs(enum_ - form) < 1e-12, `enumerated q == 1/(g(g-1)) at g=${g}`);
}

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