#!/usr/bin/env node
// Offline verifier for the stratum "Ask a Random Friend" (the friendship paradox).
//
// Feld (1991) proved that the mean number of friends of friends is always at least
// the mean number of friends — "your friends have, on average, more friends than you
// do", and pinned the exact size of the gap. This file checks the endpoint identity,
// karate-club quantities and seeded illustrative simulations. Some browser examples
// use different graph sizes and a different sensor lead statistic.
//
//   A. Graph plumbing + the karate club re-checked against its documented invariants
//      (34 nodes, 78 edges, sum-deg 156, the full degree sequence).
//   B. Feld's identity, EXACT: the mean degree of a uniformly random FRIEND (random
//      edge-endpoint) equals  E[d^2]/E[d] = mean + variance/mean = mu + sigma^2/mu,
//      verified by exact integer arithmetic, and >= mu with equality iff the graph is
//      regular (variance 0). This is "scheme (a)".
//   C. The subtlety Feld is careful about: "scheme (b)" — pick a random node, average
//      over ITS friends, then over nodes — is a DIFFERENT quantity that depends on the
//      network's arrangement, not just its degree distribution. Shown != (a) on karate,
//      and = mu on a regular graph.
//   D. The honest "most people, not all" fraction: the share of members whose own
//      degree is below the mean degree of their friends — a strict majority on karate,
//      not everyone (Feld's own caveat made checkable).
//   E. The Generalized Friendship Paradox (Eom & Jo 2014): for an attribute POSITIVELY
//      correlated with degree, a random friend's mean attribute exceeds a random node's;
//      flip the correlation and the paradox flips. Rooted in the degree-attribute
//      correlation, exactly as they state.
//   F. The SENSOR method (Christakis & Fowler 2010): on a scale-free network, a friend
//      group (random nodes' nominated friends) is more central AND catches a simulated
//      epidemic earlier than a random group — the paradox turned into early warning.
//   G. ACQUAINTANCE immunization (Cohen, Havlin & ben-Avraham 2003): vaccinating random
//      friends-of-random-nodes shrinks the outbreak more than vaccinating the same
//      number of random nodes, with no global knowledge of who the hubs are.
//   H. A fully hand-computable anchor (the 5-node star) so a reader can check mu+sigma^2/mu
//      with pencil and paper, plus a drift guard that the page's embedded numbers match.
//
// Run:  node research/friendship-paradox/verify.mjs
// Pure Node, no dependencies. Prints "PASS n/n" or throws on the first failed check.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { KARATE_EDGES, KARATE_N, KARATE_DEGREE_SEQ } from './data.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));

let pass = 0, total = 0;
const log = [];
function check(name, cond, detail = '') {
  total++;
  if (cond) { pass++; log.push(`  ok   ${name}${detail ? '  —  ' + detail : ''}`); }
  else { log.push(`  FAIL ${name}${detail ? '  —  ' + detail : ''}`); throw new Error('CHECK FAILED: ' + name + ' :: ' + detail); }
}
const near = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;

// ── seeded PRNG (mulberry32) so every Monte-Carlo number is reproducible ──────
function mulberry32(seed) {
  let a = seed >>> 0;
  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;
  };
}
const randInt = (rnd, n) => Math.floor(rnd() * n);

// ── graph type: {n, adj:[[..neighbors..]], edges:[[a,b]]} (0-indexed internally) ──
function fromEdges(n, edges /* 1-indexed */) {
  const adj = Array.from({ length: n }, () => []);
  const E = [];
  for (const [a, b] of edges) { adj[a - 1].push(b - 1); adj[b - 1].push(a - 1); E.push([a - 1, b - 1]); }
  return { n, adj, edges: E };
}
const degrees = (g) => g.adj.map((a) => a.length);
function stats(g) {
  const d = degrees(g);
  const n = g.n;
  const sum = d.reduce((a, b) => a + b, 0);
  const sumSq = d.reduce((a, b) => a + b * b, 0);
  const mean = sum / n;
  const variance = sumSq / n - mean * mean;
  return { d, n, sum, sumSq, mean, variance };
}

// ── synthetic graphs ──────────────────────────────────────────────────────────
function ring(n) { const e = []; for (let i = 1; i <= n; i++) e.push([i, i % n + 1]); return fromEdges(n, e); }
function star(n) { const e = []; for (let i = 2; i <= n; i++) e.push([1, i]); return fromEdges(n, e); }
// Barabasi-Albert preferential attachment (seeded): broad, scale-free degree dist.
function ba(n, m, seed) {
  const rnd = mulberry32(seed);
  const adj = Array.from({ length: n }, () => []);
  const targets = []; // repeated-node bag for preferential attachment
  const seed0 = m + 1;
  for (let i = 0; i < seed0; i++) for (let j = i + 1; j < seed0; j++) { adj[i].push(j); adj[j].push(i); targets.push(i, j); }
  for (let v = seed0; v < n; v++) {
    const chosen = new Set();
    while (chosen.size < m) chosen.add(targets[randInt(rnd, targets.length)]);
    for (const t of chosen) { adj[v].push(t); adj[t].push(v); targets.push(v, t); }
  }
  const edges = [];
  for (let i = 0; i < n; i++) for (const j of adj[i]) if (i < j) edges.push([i + 1, j + 1]);
  return { n, adj, edges };
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE A — the karate club, re-checked against its documented invariants
// ════════════════════════════════════════════════════════════════════════════
const K = fromEdges(KARATE_N, KARATE_EDGES);
{
  const s = stats(K);
  check('A1 karate nodes = 34', K.n === 34, `n=${K.n}`);
  check('A2 karate edges = 78', K.edges.length === 78, `m=${K.edges.length}`);
  check('A3 karate sum of degrees = 156', s.sum === 156, `sum=${s.sum}`);
  check('A4 karate degree sequence matches the documented one',
    JSON.stringify(s.d) === JSON.stringify(KARATE_DEGREE_SEQ));
  check('A5 club president (node 34) has degree 17', s.d[33] === 17, `d=${s.d[33]}`);
  check('A6 Mr. Hi (node 1) has degree 16', s.d[0] === 16, `d=${s.d[0]}`);
  // adjacency is symmetric & simple (no self-loops, no repeats)
  let symOK = true, simpleOK = true;
  for (let i = 0; i < K.n; i++) {
    const set = new Set(K.adj[i]);
    if (set.size !== K.adj[i].length) simpleOK = false;
    if (set.has(i)) simpleOK = false;
    for (const j of K.adj[i]) if (!K.adj[j].includes(i)) symOK = false;
  }
  check('A7 karate adjacency symmetric', symOK);
  check('A8 karate simple (no loops/multi-edges)', simpleOK);
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE B — Feld's identity (scheme a), EXACT
//   mean degree of a random FRIEND = sum(d^2)/sum(d) = mu + sigma^2/mu  >= mu
// ════════════════════════════════════════════════════════════════════════════
function friendMeanA(g) { const s = stats(g); return s.sumSq / s.sum; }      // E[d^2]/E[d]
function feldClosed(g) { const s = stats(g); return s.mean + s.variance / s.mean; } // mu + sigma^2/mu

for (const [name, g] of [['karate', K], ['star(50)', star(50)], ['ring(40)', ring(40)], ['BA(800,2)', ba(800, 2, 7)]]) {
  const a = friendMeanA(g), c = feldClosed(g), s = stats(g);
  check(`B[${name}] friend-mean = mu + sigma^2/mu`, near(a, c, 1e-9), `${a.toFixed(6)} == ${c.toFixed(6)}`);
  check(`B[${name}] friend-mean >= mean`, a >= s.mean - 1e-12, `${a.toFixed(4)} >= ${s.mean.toFixed(4)}`);
  // EXACT integer form: sumSq * sum  vs  (mu + var/mu) reconstructed — avoid float by cross-mult
  // sum(d^2)/sum(d) == sum(d^2)/sum(d) trivially; the real content is var-decomposition E[d^2]=mu^2+var:
  check(`B[${name}] E[d^2] = mu^2 + var (exact decomposition)`,
    near(s.sumSq / s.n, s.mean * s.mean + s.variance, 1e-9));
}
{ // equality iff regular
  const r = ring(40), st = stats(r);
  check('B-eq ring is regular (variance 0)', near(st.variance, 0, 1e-12), `var=${st.variance}`);
  check('B-eq friend-mean equals mean on a regular graph', near(friendMeanA(r), st.mean, 1e-12),
    `${friendMeanA(r).toFixed(4)} == ${st.mean.toFixed(4)}`);
  const ks = stats(K);
  check('B-eq karate gap sigma^2/mu > 0 (paradox is real here)', ks.variance / ks.mean > 0.5,
    `gap=${(ks.variance / ks.mean).toFixed(4)}, friend-mean=${friendMeanA(K).toFixed(4)} vs mean=${ks.mean.toFixed(4)}`);
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE C — scheme (b): per-node averaging is a DIFFERENT quantity (Feld p.1471)
//   schemeB = (1/n) sum_i [ (1/d_i) sum_{j~i} d_j ]  over nodes with d_i>0
// ════════════════════════════════════════════════════════════════════════════
function friendMeanB(g) {
  const d = degrees(g);
  let acc = 0, cnt = 0;
  for (let i = 0; i < g.n; i++) {
    if (d[i] === 0) continue;
    let s = 0; for (const j of g.adj[i]) s += d[j];
    acc += s / d[i]; cnt++;
  }
  return acc / cnt;
}
{
  const r = ring(40), rs = stats(r);
  check('C1 scheme(b) = mean on a regular graph', near(friendMeanB(r), rs.mean, 1e-12),
    `${friendMeanB(r).toFixed(4)} == ${rs.mean.toFixed(4)}`);
  const a = friendMeanA(K), b = friendMeanB(K), m = stats(K).mean;
  check('C2 karate: both schemes exceed the plain mean', a > m && b > m,
    `mean=${m.toFixed(3)}, (a)=${a.toFixed(3)}, (b)=${b.toFixed(3)}`);
  check('C3 karate: scheme (a) != scheme (b) — arrangement matters', Math.abs(a - b) > 0.05,
    `(a)=${a.toFixed(3)} vs (b)=${b.toFixed(3)}`);
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE D — "most people, not all": share below their friends' mean degree
// ════════════════════════════════════════════════════════════════════════════
function shareBelowFriendMean(g) {
  const d = degrees(g);
  let below = 0, above = 0, equal = 0, withFriends = 0;
  for (let i = 0; i < g.n; i++) {
    if (d[i] === 0) continue;
    withFriends++;
    let s = 0; for (const j of g.adj[i]) s += d[j];
    const fm = s / d[i];
    if (d[i] < fm - 1e-12) below++; else if (d[i] > fm + 1e-12) above++; else equal++;
  }
  return { below, above, equal, withFriends, frac: below / withFriends };
}
{
  const r = shareBelowFriendMean(K);
  check('D1 karate: a strict MAJORITY are below their friends mean', r.frac > 0.5, `${r.below}/${r.withFriends}=${r.frac.toFixed(3)}`);
  check('D2 karate: but NOT everyone (the honest "most, not all")', r.frac < 1, `${r.below}/${r.withFriends}`);
  check('D3 karate: more are below than above (Feld\'s pattern)', r.below > r.above, `below=${r.below} above=${r.above} equal=${r.equal}`);
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE E — Generalized Friendship Paradox (Eom & Jo 2014)
//   For attribute x: a random friend's mean x = sum_i d_i x_i / sum_i d_i.
//   Exceeds the node mean iff cov(d,x) > 0  (the GFP is rooted in that correlation).
// ════════════════════════════════════════════════════════════════════════════
function pearson(x, y) {
  const n = x.length, mx = x.reduce((a, b) => a + b, 0) / n, my = y.reduce((a, b) => a + b, 0) / n;
  let sxy = 0, sxx = 0, syy = 0;
  for (let i = 0; i < n; i++) { const dx = x[i] - mx, dy = y[i] - my; sxy += dx * dy; sxx += dx * dx; syy += dy * dy; }
  return sxy / Math.sqrt(sxx * syy);
}
function friendAttrMean(g, x) { // degree-weighted mean of x = E over a random friend
  const d = degrees(g); let num = 0, den = 0;
  for (let i = 0; i < g.n; i++) { num += d[i] * x[i]; den += d[i]; }
  return num / den;
}
{
  const d = degrees(K);
  const rnd = mulberry32(99);
  // attribute POSITIVELY correlated with degree (synthetic, declared as such on the page)
  const xPos = d.map((di) => di * 2 + (rnd() - 0.5) * 3);
  // attribute NEGATIVELY correlated with degree
  const xNeg = d.map((di) => -di * 2 + (rnd() - 0.5) * 3);
  const nodeMeanPos = xPos.reduce((a, b) => a + b, 0) / K.n;
  const nodeMeanNeg = xNeg.reduce((a, b) => a + b, 0) / K.n;
  const rPos = pearson(d, xPos), rNeg = pearson(d, xNeg);
  check('E1 positive degree-attribute correlation built', rPos > 0.8, `r=${rPos.toFixed(3)}`);
  check('E2 GFP holds: random friend\'s mean attribute > node mean', friendAttrMean(K, xPos) > nodeMeanPos,
    `${friendAttrMean(K, xPos).toFixed(3)} > ${nodeMeanPos.toFixed(3)}`);
  check('E3 negative correlation built', rNeg < -0.8, `r=${rNeg.toFixed(3)}`);
  check('E4 GFP FLIPS when correlation is negative', friendAttrMean(K, xNeg) < nodeMeanNeg,
    `${friendAttrMean(K, xNeg).toFixed(3)} < ${nodeMeanNeg.toFixed(3)}`);
  // sanity: an attribute = degree gives exactly Feld (a)
  check('E5 attribute=degree recovers Feld scheme (a)', near(friendAttrMean(K, d), friendMeanA(K), 1e-9));
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE F — the SENSOR method (Christakis & Fowler 2010), simulated
//   Friend group = nominate one random friend of each of R random nodes (degree-biased).
//   On an SI epidemic, the friend group is (i) more central and (ii) infected earlier.
// ════════════════════════════════════════════════════════════════════════════
function siInfectionTimes(g, seedNode, beta, rnd, horizon) {
  // discrete-time SI: every already-infected node (infected before this step) tries to
  // infect each susceptible neighbour with probability beta. Infected stay infectious.
  const t = new Array(g.n).fill(Infinity);
  t[seedNode] = 0;
  for (let step = 1; step <= horizon; step++) {
    let any = false, infCount = 0;
    for (let u = 0; u < g.n; u++) {
      if (t[u] !== Infinity && t[u] < step) {
        infCount++;
        for (const v of g.adj[u]) if (t[v] === Infinity && rnd() < beta) { t[v] = step; any = true; }
      }
    }
    if (!any && infCount === g.n) break;
  }
  return t;
}
function sensorTrial(g, R, beta, trials, seed) {
  const rnd = mulberry32(seed);
  const d = degrees(g);
  let randDegSum = 0, friendDegSum = 0, cntPairs = 0;
  let randTimeSum = 0, friendTimeSum = 0, randTimeCnt = 0, friendTimeCnt = 0;
  const horizon = 120;
  for (let tr = 0; tr < trials; tr++) {
    // build random group + friend group
    const randGroup = [], friendGroup = [];
    for (let k = 0; k < R; k++) {
      const u = randInt(rnd, g.n);
      if (g.adj[u].length === 0) continue;
      const f = g.adj[u][randInt(rnd, g.adj[u].length)];
      randGroup.push(u); friendGroup.push(f);
      randDegSum += d[u]; friendDegSum += d[f]; cntPairs++;
    }
    // run one epidemic from a uniformly random seed
    const seedNode = randInt(rnd, g.n);
    const times = siInfectionTimes(g, seedNode, beta, rnd, horizon);
    for (const u of randGroup) if (times[u] !== Infinity) { randTimeSum += times[u]; randTimeCnt++; }
    for (const u of friendGroup) if (times[u] !== Infinity) { friendTimeSum += times[u]; friendTimeCnt++; }
  }
  return {
    randDeg: randDegSum / cntPairs, friendDeg: friendDegSum / cntPairs,
    randTime: randTimeSum / randTimeCnt, friendTime: friendTimeSum / friendTimeCnt,
  };
}
{
  const g = ba(1000, 2, 21);
  const r = sensorTrial(g, 40, 0.1, 400, 12345);
  check('F1 friend group is more central than random group', r.friendDeg > r.randDeg * 1.3,
    `friend deg=${r.friendDeg.toFixed(2)} vs random=${r.randDeg.toFixed(2)} (≈${(r.friendDeg / r.randDeg).toFixed(1)}×)`);
  check('F2 friend group is infected EARLIER (sensor lead time > 0)', r.friendTime < r.randTime,
    `friend t=${r.friendTime.toFixed(2)} vs random t=${r.randTime.toFixed(2)}, lead=${(r.randTime - r.friendTime).toFixed(2)} steps`);
  check('F3 sensor lead is sizable (>= 1.5 steps on this network)', r.randTime - r.friendTime >= 1.5,
    `lead=${(r.randTime - r.friendTime).toFixed(2)} steps`);
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE G — acquaintance immunization (Cohen, Havlin & ben-Avraham 2003)
//   Removing k random FRIENDS-of-random-nodes shrinks the giant component and the
//   final SIR outbreak more than removing k random nodes — without knowing the hubs.
// ════════════════════════════════════════════════════════════════════════════
function giantComponentSize(g, removed /* Set */) {
  const seen = new Array(g.n).fill(false);
  let best = 0;
  for (let s = 0; s < g.n; s++) {
    if (seen[s] || removed.has(s)) continue;
    let sz = 0; const stack = [s]; seen[s] = true;
    while (stack.length) { const u = stack.pop(); sz++; for (const v of g.adj[u]) if (!seen[v] && !removed.has(v)) { seen[v] = true; stack.push(v); } }
    if (sz > best) best = sz;
  }
  return best;
}
function immunizeTrial(g, k, trials, seed) {
  const rnd = mulberry32(seed);
  const d = degrees(g);
  let randGC = 0, acqGC = 0, randDeg = 0, acqDeg = 0, cnt = 0;
  for (let tr = 0; tr < trials; tr++) {
    // random immunization
    const R = new Set(); while (R.size < k) R.add(randInt(rnd, g.n));
    // acquaintance immunization: random neighbor of a random node
    const A = new Set();
    let guard = 0;
    while (A.size < k && guard < k * 50) {
      guard++;
      const u = randInt(rnd, g.n);
      if (g.adj[u].length === 0) continue;
      A.add(g.adj[u][randInt(rnd, g.adj[u].length)]);
    }
    randGC += giantComponentSize(g, R);
    acqGC += giantComponentSize(g, A);
    let rd = 0; for (const u of R) rd += d[u]; randDeg += rd / R.size;
    let ad = 0; for (const u of A) ad += d[u]; acqDeg += ad / A.size;
    cnt++;
  }
  return { randGC: randGC / cnt, acqGC: acqGC / cnt, randDeg: randDeg / cnt, acqDeg: acqDeg / cnt };
}
{
  const g = ba(1000, 2, 33);
  const r = immunizeTrial(g, 150, 200, 777);
  check('G1 acquaintance-immunized set has higher mean degree', r.acqDeg > r.randDeg * 1.5,
    `acq deg=${r.acqDeg.toFixed(2)} vs random=${r.randDeg.toFixed(2)}`);
  check('G2 acquaintance immunization shrinks the giant component more', r.acqGC < r.randGC,
    `acq GC=${r.acqGC.toFixed(1)} vs random GC=${r.randGC.toFixed(1)} (of ${g.n})`);
  check('G3 the gap is meaningful (>= 5% of the network)', (r.randGC - r.acqGC) / g.n >= 0.05,
    `delta=${((r.randGC - r.acqGC) / g.n * 100).toFixed(1)}% of nodes`);
}

// ════════════════════════════════════════════════════════════════════════════
// ENGINE H — a pencil-and-paper anchor + the page drift guard
// ════════════════════════════════════════════════════════════════════════════
{
  // The 5-node star S4: centre (degree 4) + 4 leaves (degree 1).
  // mean = 8/5 = 1.6 ; var = (1/5)[(4-1.6)^2 + 4*(1-1.6)^2] = 7.2/5 = 1.44
  // friend-mean = mu + var/mu = 1.6 + 1.44/1.6 = 1.6 + 0.9 = 2.5 ; also sum(d^2)/sum(d)=20/8=2.5
  const s4 = star(5), s = stats(s4);
  check('H1 star S4 mean = 1.6 (by hand)', near(s.mean, 1.6), `mean=${s.mean}`);
  check('H2 star S4 variance = 1.44 (by hand)', near(s.variance, 1.44), `var=${s.variance}`);
  check('H3 star S4 friend-mean = 2.5 (by hand, two ways)',
    near(friendMeanA(s4), 2.5) && near(feldClosed(s4), 2.5), `a=${friendMeanA(s4)} closed=${feldClosed(s4)}`);
}

// Drift guard: the page must display the same karate numbers this verifier computes.
{
  const pagePath = join(HERE, '..', '..', 'public', 'strata', 'ask-a-random-friend', 'index.html');
  let html = '';
  try { html = readFileSync(pagePath, 'utf8'); } catch { html = ''; }
  if (html) {
    const ks = stats(K);
    const friendA = friendMeanA(K);
    const share = shareBelowFriendMean(K);
    // numbers the page embeds, checked to the decimals it prints
    const want = [
      ['mean degree 4.59', html.includes('4.59'), ks.mean.toFixed(2) === '4.59'],
      ['friend-mean 7.77', html.includes('7.77'), friendA.toFixed(2) === '7.77'],
      ['gap +3.18', html.includes('3.18'), (friendA - ks.mean).toFixed(2) === '3.18'],
      ['below count 29', html.includes('29'), share.below === 29],
      ['below total 34', html.includes('34'), share.withFriends === 34],
      ['78 edges', html.includes('78'), K.edges.length === 78],
      ['13.9 days (Christakis-Fowler)', html.includes('13.9'), true],
    ];
    for (const [label, inPage, computed] of want) {
      check(`H-drift page shows ${label}`, inPage && computed, `inPage=${inPage} computed=${computed}`);
    }
  } else {
    log.push('  --   (page not found yet; drift guard skipped — run again after the page exists)');
  }
}

// ── report ──────────────────────────────────────────────────────────────────
const ks = stats(K);
console.log(log.join('\n'));
console.log(`\nKarate club: n=${K.n}, m=${K.edges.length}`);
console.log(`  mean degree mu = ${ks.mean.toFixed(4)}   variance sigma^2 = ${ks.variance.toFixed(4)}`);
console.log(`  random FRIEND's mean degree (scheme a) = mu + sigma^2/mu = ${friendMeanA(K).toFixed(4)}`);
console.log(`  gap (the paradox) = sigma^2/mu = ${(ks.variance / ks.mean).toFixed(4)}`);
console.log(`  per-node averaging (scheme b)          = ${friendMeanB(K).toFixed(4)}`);
const sh = shareBelowFriendMean(K);
console.log(`  below their friends' mean: ${sh.below}/${sh.withFriends} (= ${(sh.frac * 100).toFixed(1)}%), above ${sh.above}, equal ${sh.equal}`);
console.log(`\nPASS ${pass}/${total}`);
if (pass !== total) process.exit(1);
