// No Two Would Rather — the math behind the stratum, verified offline first.
//
// Gale–Shapley deferred acceptance and the structure theorems of stable matching.
// Everything the page claims is re-derived and checked here, in plain Node, before
// any of it is asserted in the browser. The in-page instruments use the identical
// algorithms (deferred acceptance, the blocking-pair test, the brute-force
// stable-set enumeration); this file is the ground truth they are checked against.
//
// Run:  node research/stable-matching/verify.mjs
//
// Claims verified (with the check shown):
//   1. Deferred acceptance always outputs a STABLE matching                (no blocking pair, ever)
//   2. Proposer-OPTIMAL and receiver-PESSIMAL                             (vs the full enumerated stable set)
//   3. The set of stable matchings is a LATTICE                           (the man-join of two stable matchings is stable)
//   4. Proposing is STRATEGY-PROOF for the proposing side                 (no single misreport ever helps a proposer)
//   5. The receiving side CAN be gamed                                    (an explicit profitable misreport exists — printed)
//   6. The RURAL HOSPITALS theorem                                        (the same agents are unmatched in every stable matching)
//
// No dependencies. Deterministic PRNG so the run is reproducible.

// ---------- reproducible PRNG (mulberry32) ----------
function rng(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;
  };
}
function shuffled(n, rnd) {
  const a = [...Array(n).keys()];
  for (let i = n - 1; i > 0; i--) { const j = (rnd() * (i + 1)) | 0; [a[i], a[j]] = [a[j], a[i]]; }
  return a;
}

// ---------- preference model ----------
// A "side" is an array of preference lists; prefs[i] is i's ranking of the OTHER
// side's members, most-preferred first. Lists may be partial (incomplete prefs):
// a member not on the list is UNACCEPTABLE. rankOf[i] is a Map: member -> position,
// with Infinity for unacceptable (worse than being unmatched).
function rankTables(prefs, other) {
  return prefs.map((list) => {
    const r = new Array(other).fill(Infinity);
    list.forEach((x, pos) => { r[x] = pos; });
    return r;
  });
}
// strictly prefers a to b (b may be -1 meaning "unmatched")
const prefersTo = (rank, a, b) => (b === -1 ? rank[a] !== Infinity : rank[a] < rank[b]);

// ---------- deferred acceptance (the proposing side proposes) ----------
// Returns matchP[p] = r | -1 and matchR[r] = p | -1.
function deferredAcceptance(pPrefs, rRank, nP, nR) {
  const next = new Array(nP).fill(0);      // pointer into each proposer's list
  const matchR = new Array(nR).fill(-1);
  const matchP = new Array(nP).fill(-1);
  const free = [];
  for (let p = 0; p < nP; p++) free.push(p);
  while (free.length) {
    const p = free.pop();
    if (next[p] >= pPrefs[p].length) continue;   // p exhausted its list — stays unmatched
    const r = pPrefs[p][next[p]++];
    if (rRank[r][p] === Infinity) { free.push(p); continue; } // r finds p unacceptable
    const cur = matchR[r];
    if (cur === -1) { matchR[r] = p; matchP[p] = r; }
    else if (rRank[r][p] < rRank[r][cur]) {       // r prefers p to whom it holds
      matchR[r] = p; matchP[p] = r;
      matchP[cur] = -1; free.push(cur);
    } else { free.push(p); }                       // r keeps cur; p tries again
  }
  return { matchP, matchR };
}

// ---------- stability test (the blocking-pair search the page also runs) ----------
// A pair (p,r) BLOCKS if each strictly prefers the other to their current partner
// (an unmatched but mutually-acceptable pair blocks too). Stable = individually
// rational (no one matched to an unacceptable partner) + no blocking pair.
function blockingPairs(matchP, pRank, rRank, nP, nR) {
  const blocks = [];
  for (let p = 0; p < nP; p++) {
    for (let r = 0; r < nR; r++) {
      if (pRank[p][r] === Infinity || rRank[r][p] === Infinity) continue; // not mutually acceptable
      if (prefersTo(pRank[p], r, matchP[p]) && prefersTo(rRank[r], p, invPartner(matchP, p, r, nP))) {
        blocks.push([p, r]);
      }
    }
  }
  return blocks;
}
// r's current partner, given matchP (proposer->receiver). Helper to read it cheaply.
function invPartner(matchP, p, r, nP) {
  for (let q = 0; q < nP; q++) if (matchP[q] === r) return q;
  return -1;
}
function isStable(matchP, pRank, rRank, nP, nR) {
  // individual rationality
  for (let p = 0; p < nP; p++) if (matchP[p] !== -1 && pRank[p][matchP[p]] === Infinity) return false;
  return blockingPairs(matchP, pRank, rRank, nP, nR).length === 0;
}

// ---------- brute-force: ALL stable matchings ----------
// Recursively assign each proposer a receiver (or -1), respecting acceptability and
// one-to-one, then keep the stable assignments. Exponential, but tiny n only.
function allStableMatchings(pPrefs, pRank, rRank, nP, nR) {
  const out = [];
  const matchP = new Array(nP).fill(-1);
  const usedR = new Array(nR).fill(false);
  (function rec(p) {
    if (p === nP) {
      if (isStable(matchP, pRank, rRank, nP, nR)) out.push(matchP.slice());
      return;
    }
    // option: p unmatched
    matchP[p] = -1; rec(p + 1);
    // option: p matched to an acceptable, free receiver who also finds p acceptable
    for (const r of pPrefs[p]) {
      if (usedR[r] || rRank[r][p] === Infinity) continue;
      usedR[r] = true; matchP[p] = r; rec(p + 1); usedR[r] = false;
    }
    matchP[p] = -1;
  })(0);
  return out;
}

// the man-"join": each proposer takes the better (by his own ranking) of his two
// partners across two stable matchings. The lattice theorem says the result is stable.
function join(mA, mB, pRank) {
  return mA.map((rA, p) => {
    const rB = mB[p];
    if (rA === -1) return rB;
    if (rB === -1) return rA;
    return pRank[p][rA] <= pRank[p][rB] ? rA : rB;
  });
}

// average rank a side gets (1-indexed; lower is better), over matched agents
function avgRank(matchP, pRank) {
  let s = 0, n = 0;
  matchP.forEach((r, p) => { if (r !== -1) { s += pRank[p][r] + 1; n++; } });
  return n ? s / n : 0;
}

// =====================================================================
// THE CHECKS
// =====================================================================
let pass = 0, fail = 0;
const ok = (cond, msg) => { if (cond) { pass++; } else { fail++; console.log('  ✗ FAIL:', msg); } };

console.log('No Two Would Rather — offline verification\n' + '='.repeat(54));

// ---- 1–4 over many random complete-preference instances ----
console.log('\n[A] Random complete-preference instances (n per side):');
for (const n of [3, 4, 5, 6]) {
  let inst = 0, totalStable = 0, latticeChecks = 0, spChecks = 0;
  const TRIALS = n <= 5 ? 400 : 120;
  const rnd = rng(1000 + n);
  for (let t = 0; t < TRIALS; t++) {
    const M = Array.from({ length: n }, () => shuffled(n, rnd));
    const W = Array.from({ length: n }, () => shuffled(n, rnd));
    const mRank = rankTables(M, n), wRank = rankTables(W, n);

    // DA, men proposing
    const da = deferredAcceptance(M, wRank, n, n);
    // (1) DA output is stable
    ok(isStable(da.matchP, mRank, wRank, n, n), `DA not stable n=${n} t=${t}`);

    // full stable set
    const S = allStableMatchings(M, mRank, wRank, n, n);
    totalStable += S.length;
    ok(S.length >= 1, `no stable matching enumerated n=${n} t=${t}`);
    // DA outcome is in the set
    ok(S.some((m) => m.every((r, p) => r === da.matchP[p])), `DA outcome missing from stable set`);

    // (2) proposer-optimality: for every man, his DA partner is his BEST across all stable matchings
    for (let p = 0; p < n; p++) {
      let best = Infinity;
      for (const m of S) if (m[p] !== -1) best = Math.min(best, mRank[p][m[p]]);
      ok(da.matchP[p] !== -1 && mRank[p][da.matchP[p]] === best, `man ${p} not getting best stable partner`);
    }
    // receiver-pessimality: women get their WORST stable partner under men-proposing DA
    const daW = deferredAcceptance(W, mRank, n, n); // women proposing — women-optimal
    for (let r = 0; r < n; r++) {
      let worst = -1;
      for (const m of S) { const part = m.indexOf(r); if (part !== -1) worst = Math.max(worst, wRank[r][part]); }
      const menProposingPartner = da.matchR[r];
      ok(menProposingPartner !== -1 && wRank[r][menProposingPartner] === worst, `woman ${r} not at worst under men-proposing`);
    }

    // (3) lattice closure: join of any two stable matchings is stable
    for (let i = 0; i < S.length; i++) for (let j = i + 1; j < S.length; j++) {
      const J = join(S[i], S[j], mRank);
      ok(isStable(J, mRank, wRank, n, n) && S.some((m) => m.every((r, p) => r === J[p])),
        `join not a stable matching n=${n} t=${t}`);
      latticeChecks++;
    }

    // (4) strategy-proofness for the proposing side: no single man can misreport his
    // list (any permutation) to get a strictly better TRUE partner, under men-proposing DA.
    if (n <= 4) {
      for (let p = 0; p < n; p++) {
        const truePartnerRank = da.matchP[p] === -1 ? Infinity : mRank[p][da.matchP[p]];
        const perms = permutations([...Array(n).keys()]);
        for (const lie of perms) {
          const M2 = M.map((l, i) => (i === p ? lie : l));
          const da2 = deferredAcceptance(M2, wRank, n, n);
          const got = da2.matchP[p];
          // evaluate the OUTCOME by p's TRUE preferences
          const gotRank = got === -1 ? Infinity : mRank[p][got];
          ok(gotRank >= truePartnerRank, `man ${p} profited by lying (n=${n}, t=${t})`);
          spChecks++;
        }
      }
    }
    inst++;
  }
  console.log(`  n=${n}: ${inst} instances · avg ${(totalStable / inst).toFixed(2)} stable matchings · ` +
    `${latticeChecks} join-closure checks` + (n <= 4 ? ` · ${spChecks} proposer-lie checks` : ''));
}

// small permutation generator (n<=4 here)
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;
}

// ---- 5. the receiving side CAN be gamed — find the smallest example ----
console.log('\n[B] A profitable misreport for a receiver (the impossibility, made concrete):');
{
  // Search small random instances for one where a woman, by SUBMITTING a different
  // list (truncation counts — declaring some men unacceptable), gets a strictly
  // better TRUE partner under men-proposing DA. Then print it for the page.
  const rnd = rng(7);
  let found = null;
  for (let t = 0; t < 200000 && !found; t++) {
    const n = 3;
    const M = Array.from({ length: n }, () => shuffled(n, rnd));
    const W = Array.from({ length: n }, () => shuffled(n, rnd));
    const mRank = rankTables(M, n), wRank = rankTables(W, n);
    const base = deferredAcceptance(M, wRank, n, n);
    for (let w = 0; w < n && !found; w++) {
      const truePartner = base.matchR[w];
      const trueRank = truePartner === -1 ? Infinity : wRank[w][truePartner];
      // try every non-empty submitted list (sublist of a permutation) for w
      for (const sub of nonEmptySubsequencesOfPerms(n)) {
        const W2 = W.map((l, i) => (i === w ? sub : l));
        const wRank2 = rankTables(W2, n);
        const da2 = deferredAcceptance(M, wRank2, n, n);
        const got = da2.matchR[w];
        // the resulting matching must still be stable w.r.t. TRUE prefs to be a fair "she still ends up matched" demo;
        // but the point is only that her realized partner is better by her TRUE ranking:
        const gotRank = got === -1 ? Infinity : wRank[w][got];
        if (gotRank < trueRank) {
          found = { M, W, mRank, wRank, w, truePartner, got, submitted: sub };
          break;
        }
      }
    }
  }
  if (found) {
    const names = { m: ['Alex', 'Bo', 'Cy'], w: ['Wren', 'Yara', 'Zoë'] };
    const fmt = (list, who) => list.map((x) => names[who][x]).join(' > ');
    console.log('  Found a 3×3 instance where a receiver gains by lying. (Proposing side = the m-side.)');
    found.M.forEach((l, i) => console.log(`    ${names.m[i]}:  ${fmt(l, 'w')}`));
    found.W.forEach((l, i) => console.log(`    ${names.w[i]}:  ${fmt(l, 'm')}`));
    console.log(`    Truthful men-proposing DA gives ${names.w[found.w]} → ${found.truePartner === -1 ? 'unmatched' : names.m[found.truePartner]}` +
      ` (her rank ${found.truePartner === -1 ? '∞' : found.wRank[found.w][found.truePartner] + 1}).`);
    console.log(`    If ${names.w[found.w]} instead SUBMITS  "${found.submitted.map((x) => names.m[x]).join(' > ')}"` +
      ` she gets → ${names.m[found.got]} (her TRUE rank ${found.wRank[found.w][found.got] + 1}) — strictly better.`);
    ok(true, 'receiver-manipulation example');
  } else {
    ok(false, 'no receiver-manipulation example found (unexpected)');
  }
}
function nonEmptySubsequencesOfPerms(n) {
  // all ordered lists over {0..n-1} of length 1..n with distinct elements
  const out = [];
  (function rec(prefix, avail) {
    if (prefix.length) out.push(prefix.slice());
    for (let i = 0; i < avail.length; i++) rec([...prefix, avail[i]], avail.filter((_, j) => j !== i));
  })([], [...Array(n).keys()]);
  return out;
}

// ---- 6. the Rural Hospitals theorem (same agents unmatched in every stable matching) ----
console.log('\n[C] Rural Hospitals theorem — the unmatched set is invariant:');
{
  // Use UNBALANCED / incomplete-preference instances so some agents are unmatched.
  const rnd = rng(99);
  let inst = 0, capacityShortChecks = 0;
  for (let t = 0; t < 2000; t++) {
    const nP = 2 + ((rnd() * 3) | 0);   // 2..4 proposers
    const nR = 2 + ((rnd() * 3) | 0);   // 2..4 receivers
    // partial preference lists (each agent finds a random subset acceptable)
    const P = Array.from({ length: nP }, () => shuffled(nR, rnd).slice(0, 1 + ((rnd() * nR) | 0)));
    const R = Array.from({ length: nR }, () => shuffled(nP, rnd).slice(0, 1 + ((rnd() * nP) | 0)));
    const pRank = rankTables(P, nR), rRank = rankTables(R, nP);
    const S = allStableMatchings(P, pRank, rRank, nP, nR);
    if (S.length < 2) continue; // only interesting when there's more than one
    // the set of unmatched proposers must be identical across all stable matchings
    const unmatchedSig = (m) => m.map((r, p) => (r === -1 ? 1 : 0)).join('');
    const sig0 = unmatchedSig(S[0]);
    ok(S.every((m) => unmatchedSig(m) === sig0), `unmatched proposer-set varies (t=${t})`);
    // and the unmatched receivers too
    const unmatchedR = (m) => { const got = new Array(nR).fill(0); m.forEach((r) => { if (r !== -1) got[r] = 1; }); return got.join(''); };
    const rsig0 = unmatchedR(S[0]);
    ok(S.every((m) => unmatchedR(m) === rsig0), `unmatched receiver-set varies (t=${t})`);
    capacityShortChecks++;
    inst++;
  }
  console.log(`  ${inst} multi-stable unbalanced instances · unmatched set invariant in all (${capacityShortChecks} checks)`);
}

// =====================================================================
// EMBEDDED DEMO INSTANCES — the exact data the page ships, with derived numbers.
// =====================================================================
console.log('\n[D] The embedded demo instance (printed for the page):');
{
  // A hand-tuned 4×4 with MULTIPLE stable matchings, so the lattice is non-trivial
  // and proposer-optimal ≠ receiver-optimal is visible. Found by search, then frozen.
  // Names neutral: applicants A1..A4 propose; programs P1..P4 receive.
  const rnd = rng(424242);
  let demo = null;
  for (let t = 0; t < 500000 && !demo; t++) {
    const n = 4;
    const A = Array.from({ length: n }, () => shuffled(n, rnd));
    const P = Array.from({ length: n }, () => shuffled(n, rnd));
    const aRank = rankTables(A, n), pRank = rankTables(P, n);
    const S = allStableMatchings(A, aRank, pRank, n, n);
    if (S.length === 3) {              // exactly 3 → a clean little lattice (a chain or diamond)
      const da = deferredAcceptance(A, pRank, n, n);
      const daP = deferredAcceptance(P, aRank, n, n);
      // require proposer-opt ≠ receiver-opt (the interesting case)
      if (!da.matchP.every((r, p) => r === daP.matchP.indexOf(p))) {
        demo = { A, P, S, da, daP };
      }
    }
  }
  if (demo) {
    console.log('  4×4 with exactly 3 stable matchings (applicants A1–A4 propose; programs P1–P4):');
    demo.A.forEach((l, i) => console.log(`    A${i + 1}:  ${l.map((x) => 'P' + (x + 1)).join(' > ')}`));
    demo.P.forEach((l, i) => console.log(`    P${i + 1}:  ${l.map((x) => 'A' + (x + 1)).join(' > ')}`));
    console.log('  Stable matchings (applicant -> program):');
    demo.S.forEach((m, k) => console.log(`    S${k + 1}: ` + m.map((r, p) => `A${p + 1}→P${r + 1}`).join('  ')));
    console.log('  Applicant-proposing DA  = ' + demo.da.matchP.map((r, p) => `A${p + 1}→P${r + 1}`).join('  '));
    console.log('  (= applicant-optimal, the top of the lattice).');
    console.log('  AS JSON for embedding:');
    console.log('  ' + JSON.stringify({ A: demo.A, P: demo.P }));
  } else {
    console.log('  (no 3-stable demo found at this seed; widen search)');
  }
}

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