#!/usr/bin/env node
// Verification for the portal "Any Loop You Can Draw".
//
// The portal's claim: three layers of the Wasteland — Always Bet Second
// (Penney's game, coins), The Only Fair Vote (Condorcet/Arrow, ballots) and
// No King of the Hill (Elo, rankings) — are three faces of ONE fact: a
// "beats" relation is just a directed graph, and it need not line its members
// up in any order. A beats B beats C beats A is not a paradox; it is the
// generic shape of pairwise comparison.
//
// The load-bearing NEW thing the portal supplies, which none of the three
// layers states, is McGARVEY'S THEOREM (1953): the most trusted aggregation
// rule there is — pairwise majority vote — can manufacture LITERALLY ANY
// tournament, every cycle included. The cycle is not an exception; it is the
// full generality. We give the constructive proof as a runnable machine and
// check it reproduces every requested tournament exactly.
//
// Everything the page asserts numerically is recomputed here from scratch.
// Run:  node research/any-loop-you-can-draw/verify.mjs   (exit 0 = all pass)

let pass = 0, fail = 0;
const ok_ = (name, cond, detail = '') => {
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${cond || !detail ? '' : `\n        ${detail}`}`);
  cond ? pass++ : fail++;
};
const eqNum = (name, got, want, tol = 0) =>
  ok_(name, Math.abs(got - want) <= tol, `got ${got}  want ${want}${tol ? ` ±${tol}` : ''}`);

// ===========================================================================
// 0.  Tournaments and the majority machine.
// ===========================================================================
// A tournament on m nodes is a complete asymmetric relation: for every pair
// {i,j}, exactly one of i→j ("i beats j") or j→i. We store it as an m×m matrix
// T with T[i][j] = 1 iff i beats j.
//
// A "voter" is a strict ranking (a permutation): rank[0] is the favourite.
// prefers(rank, i, j) = voter ranks i above j.
const prefers = (rank, i, j) => rank.indexOf(i) < rank.indexOf(j);

// majorityTournament: given a list of voters (rankings) over m alternatives,
// return the strict pairwise-majority tournament, or report a tie.
function majorityTournament(voters, m) {
  const T = Array.from({ length: m }, () => Array(m).fill(0));
  let tie = false;
  for (let i = 0; i < m; i++) for (let j = i + 1; j < m; j++) {
    let ai = 0, aj = 0;
    for (const v of voters) (prefers(v, i, j) ? ai++ : aj++);
    if (ai === aj) { tie = true; T[i][j] = T[j][i] = 0; }
    else if (ai > aj) T[i][j] = 1; else T[j][i] = 1;
  }
  return { T, tie };
}

// ---------------------------------------------------------------------------
// McGarvey's construction. For each edge x→y we want, add TWO voters that
// agree on x>y but are mirror images on everything else, so every OTHER pair
// gets one vote each way and cancels — leaving a net +2 margin on (x,y) alone.
//
//   voter A:  x , y , rest-in-order
//   voter B:  rest-reversed , x , y
//
// Summed over all edges of the target T, the margin on (a,b) is +2 iff a→b∈T
// and 0 elsewhere — so the majority tournament IS T, exactly.
function mcGarveyVoters(T, m) {
  const voters = [];
  for (let x = 0; x < m; x++) for (let y = 0; y < m; y++) {
    if (T[x][y] !== 1) continue;                 // only the edges we want
    const rest = [];
    for (let k = 0; k < m; k++) if (k !== x && k !== y) rest.push(k);
    voters.push([x, y, ...rest]);                // A
    voters.push([...rest.slice().reverse(), x, y]); // B
  }
  return voters;
}

const sameT = (A, B, m) => {
  for (let i = 0; i < m; i++) for (let j = 0; j < m; j++) if (A[i][j] !== B[i][j]) return false;
  return true;
};

// ---------------------------------------------------------------------------
console.log('\n=== I.  McGarvey: votes can build ANY tournament ===\n');

// All 8 tournaments on 3 labelled nodes (each of the 3 pairs points 2 ways).
{
  let reproduced = 0, cyclic = 0, transitive = 0;
  const all3 = [];
  for (let bits = 0; bits < 8; bits++) {
    const T = [[0,0,0],[0,0,0],[0,0,0]];
    // pairs (0,1),(0,2),(1,2); bit=0 → first beats second, bit=1 → reverse
    const pairs = [[0,1],[0,2],[1,2]];
    pairs.forEach(([a,b], k) => { if ((bits >> k) & 1) T[b][a]=1; else T[a][b]=1; });
    all3.push(T);
    const voters = mcGarveyVoters(T, 3);
    const { T: M, tie } = majorityTournament(voters, 3);
    if (!tie && sameT(M, T, 3)) reproduced++;
    // classify: cyclic iff every node beats exactly one (out-degrees all 1)
    const outdeg = [0,1,2].map(i => T[i].reduce((s,x)=>s+x,0));
    if (outdeg.every(d => d === 1)) cyclic++; else transitive++;
  }
  ok_('all 8 three-node tournaments reproduced exactly by majority vote', reproduced === 8, `reproduced ${reproduced}/8`);
  ok_('exactly 2 of the 8 are 3-cycles (rock-paper-scissors), 6 are transitive', cyclic === 2 && transitive === 6, `cyclic ${cyclic}, transitive ${transitive}`);
  ok_('McGarvey uses m(m-1)=6 voters for m=3', mcGarveyVoters(all3[0], 3).length === 6, `${mcGarveyVoters(all3[0],3).length} voters`);
}

// The canonical Condorcet 3-cycle 0→1→2→0, built from voters, checked.
{
  const T = [[0,1,0],[0,0,1],[1,0,0]];          // 0 beats 1, 1 beats 2, 2 beats 0
  const voters = mcGarveyVoters(T, 3);
  const { T: M, tie } = majorityTournament(voters, 3);
  ok_('the rock-paper-scissors cycle is a real majority preference (no tie)', !tie && sameT(M, T, 3));
  // ...and it has NO Condorcet winner (no node beats both others).
  const winner = [0,1,2].find(i => T[i].reduce((s,x)=>s+x,0) === 2);
  ok_('the cycle has NO Condorcet winner (nobody beats everyone)', winner === undefined);
}

// Random tournaments on n = 4,5,6: McGarvey reproduces every one.
{
  // small reproducible PRNG (mulberry32)
  let seed = 0x9e3779b9 >>> 0;
  const rnd = () => { seed |= 0; seed = (seed + 0x6D2B79F5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  for (const m of [4, 5, 6]) {
    let good = 0, trials = 400;
    let maxVoters = 0;
    for (let t = 0; t < trials; t++) {
      const T = Array.from({ length: m }, () => Array(m).fill(0));
      for (let i = 0; i < m; i++) for (let j = i + 1; j < m; j++) (rnd() < 0.5 ? T[i][j] = 1 : T[j][i] = 1);
      const voters = mcGarveyVoters(T, m);
      maxVoters = Math.max(maxVoters, voters.length);
      const { T: M, tie } = majorityTournament(voters, m);
      if (!tie && sameT(M, T, m)) good++;
    }
    ok_(`m=${m}: all ${trials} random tournaments reproduced exactly`, good === trials, `${good}/${trials}`);
    ok_(`m=${m}: voter count is exactly m(m-1)=${m*(m-1)}`, maxVoters === m * (m - 1), `${maxVoters}`);
  }
}

// ===========================================================================
console.log('\n=== II.  The cycle is generic, not exceptional ===\n');
// ===========================================================================

// Exact small case (cross-checks the sibling layer "The Only Fair Vote",
// which states "exactly 12 of the 216 three-voter ballots cycle").
{
  const perms = [];
  const permute = (arr, cur = []) => { if (!arr.length) return perms.push(cur); for (let i=0;i<arr.length;i++) permute([...arr.slice(0,i),...arr.slice(i+1)], [...cur, arr[i]]); };
  permute([0, 1, 2]);                            // the 6 strict rankings
  let cyclic = 0, total = 0;
  for (const a of perms) for (const b of perms) for (const c of perms) {
    total++;
    const { T } = majorityTournament([a, b, c], 3);
    const outdeg = [0,1,2].map(i => T[i].reduce((s,x)=>s+x,0));
    if (outdeg.every(d => d === 1)) cyclic++;     // a 3-cycle = no Condorcet winner
  }
  ok_('3 voters × 3 options: 216 profiles, exactly 12 cycle (= 1/18)', total === 216 && cyclic === 12, `total ${total}, cyclic ${cyclic}`);
  eqNum('that cyclic fraction = 1/18 ≈ 0.0556', cyclic / total, 1 / 18, 1e-12);
}

// Monte-Carlo impartial culture: as the electorate grows, the probability of a
// cyclic majority on 3 options climbs toward Guilbaud's number ≈ 0.08774.
{
  let seed = 12345 >>> 0;
  const rnd = () => { seed |= 0; seed = (seed + 0x6D2B79F5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  // a fast majority-on-3 using running margins, voter = uniform of 6 rankings
  const RANK = [[0,1,2],[0,2,1],[1,0,2],[1,2,0],[2,0,1],[2,1,0]];
  function cyclicRate(n, trials) {
    let cyc = 0;
    for (let t = 0; t < trials; t++) {
      let m01 = 0, m02 = 0, m12 = 0;             // margin of first over second
      for (let v = 0; v < n; v++) {
        const r = RANK[(rnd() * 6) | 0];
        const p = (i, j) => r.indexOf(i) < r.indexOf(j) ? 1 : -1;
        m01 += p(0,1); m02 += p(0,2); m12 += p(1,2);
      }
      // edges: 0>1 if m01>0 etc. cyclic iff (0>1,1>2,2>0) or (1>0,2>1,0>2)
      const e01 = m01 > 0, e12 = m12 > 0, e02 = m02 > 0;
      if ((e01 && e12 && !e02) || (!e01 && !e12 && e02)) cyc++;
    }
    return cyc / trials;
  }
  const GUILBAUD = 0.0877398280; // Guilbaud's number (1952), 3-alt n→∞ limit
  // Verified closed form (one of several equivalent): arcsin(√6/9)/π.
  eqNum('Guilbaud closed form arcsin(√6/9)/π = 0.0877398', Math.asin(Math.sqrt(6) / 9) / Math.PI, GUILBAUD, 1e-9);
  const r999 = cyclicRate(999, 120000);
  eqNum(`impartial culture, n=999 voters: P(cycle) ≈ Guilbaud ${GUILBAUD.toFixed(4)}`, r999, GUILBAUD, 0.01);
  const r3 = cyclicRate(3, 200000);
  eqNum('impartial culture, n=3 voters: P(cycle) ≈ 1/18 (matches the exact count)', r3, 1/18, 0.006);
  ok_('P(cycle) rises with the electorate: P(n=999) > P(n=3)', r999 > r3, `n=3 → ${r3.toFixed(4)},  n=999 → ${r999.toFixed(4)}`);
}

// The same, but growing the number of OPTIONS (impartial culture, large n):
// the chance there is no Condorcet winner rises toward 1 as options multiply.
{
  let seed = 777 >>> 0;
  const rnd = () => { seed |= 0; seed = (seed + 0x6D2B79F5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  // random strict ranking via Fisher–Yates
  const shuffle = (m) => { const a = [...Array(m).keys()]; for (let i=m-1;i>0;i--){ const j=(rnd()*(i+1))|0; [a[i],a[j]]=[a[j],a[i]]; } return a; };
  function noCondorcetRate(m, n, trials) {
    let bad = 0;
    for (let t = 0; t < trials; t++) {
      // margins matrix
      const M = Array.from({length:m},()=>Array(m).fill(0));
      for (let v=0; v<n; v++){ const r=shuffle(m); const pos=Array(m); r.forEach((x,idx)=>pos[x]=idx);
        for(let i=0;i<m;i++)for(let j=i+1;j<m;j++){ if(pos[i]<pos[j]){M[i][j]++;M[j][i]--;}else{M[j][i]++;M[i][j]--;} } }
      // Condorcet winner = beats all others pairwise
      let hasWinner = false;
      for (let i=0;i<m && !hasWinner;i++){ let all=true; for(let j=0;j<m;j++) if(j!==i && M[i][j]<=0){all=false;break;} if(all) hasWinner=true; }
      if (!hasWinner) bad++;
    }
    return bad / trials;
  }
  // NOTE: these are MEASURED simulation values for a large but finite electorate
  // (n=301, impartial culture) — NOT cited published n→∞ limits. What is rigorous
  // (Niemi–Weisberg 1968; Gehrlein) is the *monotone rise toward 1*; the exact
  // limit constants for m≥4 vary by source, so we only report what we simulate.
  const p3 = noCondorcetRate(3, 301, 30000);
  const p5 = noCondorcetRate(5, 301, 30000);
  const p7 = noCondorcetRate(7, 301, 30000);
  ok_('P(no Condorcet winner) rises with options: m=3 < m=5 < m=7',
      p3 < p5 && p5 < p7, `m3 ${p3.toFixed(3)}, m5 ${p5.toFixed(3)}, m7 ${p7.toFixed(3)}`);
  eqNum('m=3 (n=301 sim) ≈ Guilbaud 0.0877', p3, 0.0877, 0.012);
  ok_('m=5 (n=301 sim) is roughly a quarter (0.20–0.30)', p5 > 0.20 && p5 < 0.30, `${p5.toFixed(3)}`);
  ok_('m=7 (n=301 sim) is past a third (>0.33)', p7 > 0.33, `${p7.toFixed(3)}`);
}

// ===========================================================================
console.log('\n=== III.  The same loop, in the wild — three known instances ===\n');
// ===========================================================================

// (a) Efron's intransitive dice — a 4-cycle, each beats the next w.p. 2/3.
{
  const A=[4,4,4,4,0,0], B=[3,3,3,3,3,3], C=[6,6,2,2,2,2], D=[5,5,5,1,1,1];
  const beatProb = (X, Y) => { let w=0,tot=0; for(const x of X) for(const y of Y){ tot++; if(x>y) w++; } return w/tot; };
  eqNum('Efron: P(A beats B) = 2/3', beatProb(A,B), 2/3, 1e-12);
  eqNum('Efron: P(B beats C) = 2/3', beatProb(B,C), 2/3, 1e-12);
  eqNum('Efron: P(C beats D) = 2/3', beatProb(C,D), 2/3, 1e-12);
  eqNum('Efron: P(D beats A) = 2/3', beatProb(D,A), 2/3, 1e-12);
  ok_('Efron dice close the loop A→B→C→D→A (each > 1/2)',
      [beatProb(A,B),beatProb(B,C),beatProb(C,D),beatProb(D,A)].every(p=>p>0.5));
}

// (b) Penney's game — a coin cross-check of the sibling "Always Bet Second".
// race(p1, p2) = P(pattern p2 completes before p1) in a fair coin, by an exact
// automaton DP over the proper prefixes of both patterns; depth 200 leaves the
// unabsorbed mass far below 1e-9.
function race(p1, p2) {
  const pref = new Set(['']);
  for (const p of [p1, p2]) for (let L = 1; L < p.length; L++) pref.add(p.slice(0, L));
  const step = (s, b) => {
    const t = s + b;
    if (t.endsWith(p2)) return { win: 'p2' };
    if (t.endsWith(p1)) return { win: 'p1' };
    for (let L = Math.min(t.length, p1.length - 1); L >= 0; L--) { const suf = t.slice(t.length - L); if (pref.has(suf)) return { next: suf }; }
    return { next: '' };
  };
  let dist = new Map([['', 1]]), w2 = 0;
  for (let d = 0; d < 200; d++) { const nd = new Map();
    for (const [s, m] of dist) for (const b of ['H', 'T']) { const r = step(s, b), w = m / 2;
      if (r.win === 'p2') w2 += w; else if (r.win === 'p1') {} else nd.set(r.next, (nd.get(r.next) || 0) + w); }
    dist = nd; }
  return w2;
}
{
  // Against HHH, the response THH wins with probability 7/8: HHH can only win on
  // the opening three flips (prob 1/8); any earlier T arms THH first.
  eqNum('Penney: P(THH beats HHH) = 7/8', race('HHH', 'THH'), 7/8, 1e-9);
  eqNum('Penney: P(HHH beats THH) = 1/8', race('THH', 'HHH'), 1/8, 1e-9);

  // The full 8-triple tournament has no 3-cycle but a real 4-CYCLE among
  // HHT → HTT → TTH → THH → HHT (the ring the gallery draws), each beating the
  // next by 2:1 or 3:1 — "four of the eight triples in a ring" (Always Bet Second).
  const ring = ['HHT', 'HTT', 'TTH', 'THH'];
  let closes = true; const odds = [];
  for (let i = 0; i < 4; i++) {
    const pWinnerFirst = race(ring[(i + 1) % 4], ring[i]); // P(ring[i] completes before ring[i+1])
    odds.push(pWinnerFirst.toFixed(3));
    if (pWinnerFirst <= 0.5) closes = false;
  }
  ok_('Penney 4-cycle HHT→HTT→TTH→THH→HHT closes (each beats the next > ½)', closes, `P(winner first) per edge: ${odds.join(', ')}`);

  // ...and there is NO 3-cycle among the eight triples — its smallest loop is the 4-ring.
  const pats = [];
  for (const a of 'HT') for (const b of 'HT') for (const c of 'HT') pats.push(a + b + c);
  const beats = pats.map(() => pats.map(() => 0));
  for (let i = 0; i < 8; i++) for (let j = 0; j < 8; j++) if (i !== j && race(pats[j], pats[i]) > 0.5) beats[i][j] = 1;
  let has3 = false;
  for (let i = 0; i < 8; i++) for (let j = 0; j < 8; j++) for (let k = 0; k < 8; k++)
    if (i!==j&&j!==k&&i!==k && beats[i][j] && beats[j][k] && beats[k][i]) has3 = true;
  ok_('Penney has no 3-cycle (its smallest loop is the 4-ring)', !has3);
}

console.log(`\n${'='.repeat(58)}\n${pass} passed, ${fail} failed\n`);
process.exit(fail ? 1 : 0);
