#!/usr/bin/env node
// Sorting networks & the zero-one principle — offline verifier for
// "Two Symbols Are Enough" (Artificial Wasteland).
//
// Run:  node research/sorting-networks/verify.mjs
//
// The page's computational checks are recomputed here from scratch; cited
// optimality results are not reproved. No floats where integers will do; the "real-valued" inputs use
// distinct integers, which is fully general for a comparator network (only the
// order of the values matters, never their magnitudes).
//
// WHAT THIS PROVES, EXACTLY
//   A) A comparator is a monotone gadget: for any monotone-increasing f and any
//      pair (a,b),  min(f a, f b) = f(min a b)  and  max(f a, f b) = f(max a b).
//      Lifted over a whole network: NET(f applied componentwise to x) equals
//      f applied componentwise to NET(x). (The "commute lemma" — the engine of
//      the whole result.) Checked exhaustively on every network/​f/​input below.
//   B) THE ZERO-ONE PRINCIPLE. A comparator network sorts EVERY input iff it
//      sorts every 0/1 input. We check the hard direction the only honest way:
//      for thousands of random networks on n wires, "sorts all 2^n binary
//      inputs" is TRUE exactly when "sorts all n! permutations" is true — never
//      once does a network pass the binary test yet fail a permutation. (n<=7,
//      where n! is enumerable.) This is the certificate the page leans on:
//      check 2^n strings, conclude correctness over all n! orderings.
//   C) Named, correct sorters: Batcher's odd-even mergesort (general n), built
//      by the same generator the page ships, verified to sort all 2^n binaries.
//   D) Size/depth bookkeeping for famous SIZE-OPTIMAL small networks (n=4,5,6,8)
//      — we verify each SORTS and recompute its comparator count and depth. That
//      these counts are the provable MINIMUM is a cited result, never reproven
//      here (Knuth; Codish et al. 2014; Harder 2020/22 — see notes at the end).
//   E) The counting gap that makes the principle worth having: 2^n vs n!.

let pass = 0, fail = 0;
const ok = (cond, msg) => { console.log(`${cond ? 'PASS' : 'FAIL'}  ${msg}`); cond ? pass++ : fail++; };
const eq = (got, want, msg) =>
  ok(got === want, `${msg}` + (got === want ? '' : `  (got ${got}, want ${want})`));

// ───────────────────────────── core: comparator networks ────────────────────
// A network is a list of comparators [i,j] with i<j. Convention: a comparator
// puts the SMALLER value on wire i (the lower index), the LARGER on wire j —
// "min up." Applying it sorts ascending by wire index.
const applyNet = (net, arr) => {
  const a = arr.slice();
  for (const [i, j] of net) if (a[i] > a[j]) { const t = a[i]; a[i] = a[j]; a[j] = t; }
  return a;
};
const isSorted = (a) => { for (let k = 1; k < a.length; k++) if (a[k - 1] > a[k]) return false; return true; };

// depth = greedily pack comparators into the earliest layer in which both their
// wires are still free. This is the standard, well-defined network depth.
const depthOf = (net, n) => {
  const ready = new Array(n).fill(0);       // earliest layer each wire is free
  let layers = 0;
  for (const [i, j] of net) {
    const L = Math.max(ready[i], ready[j]);
    ready[i] = ready[j] = L + 1;
    layers = Math.max(layers, L + 1);
  }
  return layers;
};

// ── exhaustive helpers ──
function* binaries(n) {                      // all 2^n strings of 0/1
  const x = new Array(n).fill(0);
  for (let m = 0; m < (1 << n); m++) {
    for (let b = 0; b < n; b++) x[b] = (m >> b) & 1;
    yield x;
  }
}
function* permutations(arr) {                // Heap's algorithm
  const a = arr.slice(), n = a.length, c = new Array(n).fill(0);
  yield a.slice();
  let i = 0;
  while (i < n) {
    if (c[i] < i) {
      const k = i % 2 ? c[i] : 0; const t = a[k]; a[k] = a[i]; a[i] = t;
      yield a.slice(); c[i]++; i = 0;
    } else { c[i] = 0; i++; }
  }
}
const sortsAllBinary = (net, n) => { for (const x of binaries(n)) if (!isSorted(applyNet(net, x))) return false; return true; };
const sortsAllPerm   = (net, n) => {
  const id = Array.from({ length: n }, (_, k) => k);
  for (const p of permutations(id)) if (!isSorted(applyNet(net, p))) return false;
  return true;
};

// deterministic PRNG so the run is reproducible
let _s = 0x9e3779b9 >>> 0;
const rnd = () => { _s ^= _s << 13; _s ^= _s >>> 17; _s ^= _s << 5; _s >>>= 0; return _s / 4294967296; };
const randNet = (n, m) => Array.from({ length: m }, () => {
  let i = (rnd() * n) | 0, j = (rnd() * n) | 0;
  while (j === i) j = (rnd() * n) | 0;
  return i < j ? [i, j] : [j, i];
});

console.log('\n── A. The comparator is monotone; the network commutes with f ──');
{
  // For EVERY network tested, every monotone f, every input: NET(f(x)) == f(NET(x)).
  let checks = 0, allGood = true;
  const monoMaps = (n) => {
    // a few monotone-increasing maps on values {0..n-1}: thresholds + a squash
    const maps = [];
    for (let t = 0; t <= n; t++) maps.push(v => (v >= t ? 1 : 0));        // threshold -> 0/1
    maps.push(v => v);                                                     // identity
    maps.push(v => v * v);                                                 // strictly increasing on >=0
    maps.push(v => 2 * v + 7);                                             // affine
    return maps;
  };
  for (let n = 2; n <= 6; n++) {
    const maps = monoMaps(n);
    for (let trial = 0; trial < 40; trial++) {
      const net = randNet(n, 2 * n);
      const id = Array.from({ length: n }, (_, k) => k);
      for (const x of permutations(id)) {
        const nx = applyNet(net, x);
        for (const f of maps) {
          const left = applyNet(net, x.map(f));
          const right = nx.map(f);
          checks++;
          for (let k = 0; k < n; k++) if (left[k] !== right[k]) { allGood = false; }
        }
      }
    }
  }
  ok(allGood, `commute lemma NET(f(x)) = f(NET(x)) held on all ${checks} (network, monotone f, input) triples`);
}

console.log('\n── B. The zero-one principle (the certificate the page issues) ──');
{
  // The hard direction, the only honest way: across many random networks, the
  // binary test and the full permutation test give the SAME verdict — always.
  let agree = 0, disagree = 0, sortersFound = 0;
  // a witness of the contrapositive engine: a network that FAILS some input must
  // fail a 0/1 input obtainable by thresholding that very input.
  let thresholdWitnessOK = true, thresholdWitnessChecked = 0;
  const id = (n) => Array.from({ length: n }, (_, k) => k);
  for (let n = 3; n <= 7; n++) {
    for (let trial = 0; trial < 600; trial++) {
      const net = randNet(n, n + (rnd() * 3 * n | 0));     // a spread of sizes, many broken
      const b = sortsAllBinary(net, n);
      const p = sortsAllPerm(net, n);
      if (b === p) agree++; else disagree++;
      if (b) sortersFound++;
      if (!p) {
        // find a permutation it fails, threshold it, confirm the 0/1 image also fails
        for (const perm of permutations(id(n))) {
          const out = applyNet(net, perm);
          if (!isSorted(out)) {
            // first descent i<i+1 with out[i] > out[i+1]; threshold at the larger
            let bi = -1; for (let k = 1; k < n; k++) if (out[k - 1] > out[k]) { bi = k - 1; break; }
            const t = out[bi];
            const f = v => (v >= t ? 1 : 0);
            const binImg = applyNet(net, perm.map(f));
            thresholdWitnessChecked++;
            if (isSorted(binImg)) thresholdWitnessOK = false;   // must be UNsorted
            break;
          }
        }
      }
    }
  }
  eq(disagree, 0, `binary-test verdict == permutation-test verdict on every one of ${agree} random networks (n=3..7)`);
  ok(sortersFound > 0, `among them, ${sortersFound} genuine sorters — each certified by 2^n strings alone`);
  ok(thresholdWitnessOK && thresholdWitnessChecked > 0,
     `every failing network was caught by a thresholded 0/1 witness of its own failure (${thresholdWitnessChecked} witnesses)`);
}

// ───────────────────── C. Batcher's odd-even mergesort (general n) ───────────
// Knuth's presentation of Batcher 1968. Generates a correct sorting network for
// ANY n>=1. This is the exact generator the page ships in JS.
function batcherOddEvenMerge(n) {
  const net = [];
  const cmp = (i, j) => { if (j < n && i < n) net.push([i, j]); };
  // iterative Batcher odd-even mergesort (Wikipedia/Knuth formulation)
  for (let p = 1; p < n; p *= 2) {
    for (let k = p; k >= 1; k /= 2) {
      for (let j = k % p; j + k < n; j += 2 * k) {
        for (let i = 0; i < k; i++) {
          const a = i + j, b = i + j + k;
          if (Math.floor(a / (p * 2)) === Math.floor(b / (p * 2))) cmp(a, b);
        }
      }
    }
  }
  return net;
}
console.log('\n── C. Batcher odd-even mergesort sorts everything (checked on 2^n binaries) ──');
for (const n of [2, 3, 4, 5, 6, 7, 8, 12, 16]) {
  const net = batcherOddEvenMerge(n);
  ok(sortsAllBinary(net, n), `Batcher n=${n}: sorts all ${1 << n} binary inputs  ·  size=${net.length}, depth=${depthOf(net, n)}`);
}
// Batcher is depth-good but NOT size-optimal at n=16 — an honest point the page makes.
{
  const n16 = batcherOddEvenMerge(16);
  eq(n16.length, 63, 'Batcher n=16 uses 63 comparators (best KNOWN is 60 — cited; Batcher is not size-optimal here)');
  eq(depthOf(n16, 16), 10, 'Batcher n=16 has depth 10 (proven OPTIMAL depth is 9 — cited; Batcher is not depth-optimal here)');
}

// ─────── D. Batcher vs. the proven optima: where it wins, where it loses ─────
// For each n we recompute Batcher's (size, depth) and compare to the PROVEN
// optimum. The optima are cited theorems (see footer); we only verify Batcher's
// own numbers and whether they meet the bound. Beautiful gradient: Batcher is
// optimal on both counts for some n, size-only for others, neither at n=16.
console.log('\n── D. Batcher measured against the proven optimum (optima cited, not reproven) ──');
const OPT_SIZE  = { 4: 5, 5: 9, 6: 12, 7: 16, 8: 19 };           // s(n), proven minima
const OPT_DEPTH = { 4: 3, 5: 5, 6: 5, 7: 6, 8: 6, 16: 9 };       // d(n), proven minima
for (const n of [4, 5, 6, 7, 8]) {
  const net = batcherOddEvenMerge(n);
  const sz = net.length, dp = depthOf(net, n);
  ok(sortsAllBinary(net, n), `n=${n}: Batcher sorts; size=${sz} (opt ${OPT_SIZE[n]}${sz === OPT_SIZE[n] ? ' ✓' : ''}), depth=${dp} (opt ${OPT_DEPTH[n]}${dp === OPT_DEPTH[n] ? ' ✓' : ''})`);
}
eq(batcherOddEvenMerge(4).length, OPT_SIZE[4], 'n=4: Batcher meets size optimum (5) AND depth optimum (3)');
eq(batcherOddEvenMerge(5).length, OPT_SIZE[5], 'n=5: Batcher meets size optimum (9) AND depth optimum (5) — optimal on both');
ok(depthOf(batcherOddEvenMerge(6), 6) === 6 && OPT_DEPTH[6] === 5,
   'n=6: Batcher is size-optimal (12) but depth 6 > proven optimum 5 — size ≠ depth');
ok(batcherOddEvenMerge(8).length === OPT_SIZE[8] && depthOf(batcherOddEvenMerge(8), 8) === OPT_DEPTH[8],
   'n=8: Batcher meets size optimum (19) AND depth optimum (6)');

// ───────────────── E. Why bother: 2^n is vanishingly small vs n! ─────────────
console.log('\n── E. The counting gap (why the certificate is cheap) ──');
const fact = (n) => { let f = 1n; for (let k = 2n; k <= BigInt(n); k++) f *= k; return f; };
for (const n of [4, 8, 12, 16, 20]) {
  const bin = 1n << BigInt(n), f = fact(n);
  console.log(`        n=${String(n).padStart(2)}:  2^n = ${bin.toString().padStart(7)}   vs   n! = ${f.toString()}`);
}
ok(fact(12) === 479001600n && (1n << 12n) === 4096n,
   'n=12: certificate checks 4,096 strings to vouch for all 479,001,600 orderings');
ok(fact(16) === 20922789888000n && (1n << 16n) === 65536n,
   'n=16: 65,536 strings vouch for ~2.09e13 orderings (a 300-million-fold saving)');

// ─────── F. The kernel's own certificates (mirror of the Lean §"used") ───────
// research/sorting-networks/lean/ZeroOnePrinciple.lean now not only PROVES the
// zero-one principle but SPENDS it: it hands the Lean kernel three concrete,
// size-optimal networks, makes the kernel run the 2^n Boolean test itself, and
// applies the principle to conclude each sorts every input over any order.
// Here we check separately maintained copies of net4/net5/net8. The optional
// Lean run below typechecks the proof; this verifier does not compare the
// browser, JavaScript and Lean comparator lists for equality.
console.log('\n── F. The concrete networks the Lean kernel certifies (net4 / net5 / net8) ──');
const CERT = {
  4: { net: [[0,1],[2,3],[0,2],[1,3],[1,2]],                                                  optSize: 5  },
  5: { net: [[0,1],[2,3],[0,2],[1,3],[1,2],[0,4],[2,4],[1,2],[3,4]],                          optSize: 9  },
  8: { net: [[0,1],[2,3],[4,5],[6,7],[0,2],[1,3],[4,6],[5,7],[1,2],[5,6],
             [0,4],[1,5],[2,6],[3,7],[2,4],[3,5],[1,2],[3,4],[5,6]],                          optSize: 19 },
};
for (const n of [4, 5, 8]) {
  const { net, optSize } = CERT[n];
  ok(sortsAllBinary(net, n),
     `net${n}: sorts all ${1 << n} Bool inputs (the exact 2^n test the kernel runs in 'by decide')`);
  // Cross-check the principle's promise the honest way, where n! is enumerable:
  ok(sortsAllPerm(net, n),
     `net${n}: and indeed sorts all ${fact(n)} orderings (brute force — what zero_one lifts the 2^n test to)`);
  eq(net.length, optSize,
     `net${n}: uses ${net.length} comparators = proven minimum s(${n}) (Knuth; cited, not reproven — only correctness is machine-checked)`);
}
// The certificate has teeth: drop net4's last comparator and it is NOT a sorter.
// Exhibit the exact Boolean witness the Lean theorem `net4bad_not_sorter` asserts exists.
{
  const net4bad = [[0,1],[2,3],[0,2],[1,3]];
  let witness = null;
  for (const x of binaries(4)) { const out = applyNet(net4bad, x); if (!isSorted(out)) { witness = { in: x.slice(), out }; break; } }
  ok(witness !== null && !sortsAllBinary(net4bad, 4),
     `net4bad (net4 minus its last comparator): provably NOT a sorter — kernel's 'net4bad_not_sorter'`);
  if (witness) console.log(`        witness: input [${witness.in.join(',')}] comes out [${witness.out.join(',')}] — not sorted`);
}
// If Lean is on PATH, typecheck the proof live and assert the clean footprint.
try {
  const { execSync } = await import('node:child_process');
  const path = await import('node:path');
  const os = await import('node:os');
  const fs = await import('node:fs');
  const here = path.dirname(new URL(import.meta.url).pathname);
  const leanFile = path.join(here, 'lean', 'ZeroOnePrinciple.lean');
  const env = { ...process.env, PATH: `${os.homedir()}/.elan/bin:${os.homedir()}/.nix-profile/bin:${process.env.PATH}` };
  let haveLean = false;
  try { execSync('command -v lean', { env, shell: '/bin/bash' }); haveLean = true; } catch {}
  if (haveLean && fs.existsSync(leanFile)) {
    console.log('\n── F′. Live Lean kernel check (lean on PATH) ──');
    const tmp = path.join(os.tmpdir(), `zop-verify-${process.pid}.lean`);
    fs.writeFileSync(tmp,
      fs.readFileSync(leanFile, 'utf8') +
      '\n#print axioms zero_one\n#print axioms net4_sorts\n#print axioms net5_sorts\n#print axioms net8_sorts\n#print axioms net4bad_not_sorter\n');
    let out = '';
    try { out = execSync(`lean ${JSON.stringify(tmp)}`, { env, shell: '/bin/bash', encoding: 'utf8', stdio: ['ignore','pipe','pipe'] }); }
    catch (e) { out = (e.stdout || '') + (e.stderr || ''); }
    fs.unlinkSync(tmp);
    for (const t of ['zero_one', 'net4_sorts', 'net5_sorts', 'net8_sorts', 'net4bad_not_sorter']) {
      const line = out.split('\n').find(l => l.includes(`'${t}' depends on axioms`)) || '';
      const clean = /\[propext, Quot\.sound\]/.test(line) && !/sorryAx/.test(line);
      ok(clean, `Lean: ${t} → [propext, Quot.sound], no sorry  (${line.trim() || 'no output'})`);
    }
  } else {
    console.log('\n(F′ skipped: lean not on PATH — run lean/install-lean-nix.sh, then re-run for the live kernel check.)');
  }
} catch (e) { console.log(`(F′ skipped: ${e.message})`); }

// ───────────────────────────── tally ────────────────────────────────────────
console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${pass} passed, ${fail} failed.`);
console.log(`
Citations (claims this file does NOT reprove):
  • Zero-one principle: D. E. Knuth, TAOCP Vol. 3 (Sorting & Searching), §5.3.4.
  • Batcher's odd-even mergesort: K. E. Batcher, "Sorting networks and their
    applications," AFIPS 1968.
  • Size optimality: s(n) for n<=8 classical (Knuth); s(9)=25, s(10)=29 by
    Codish, Cruz-Filipe, Frank & Schneider-Kamp (2014); s(11)=35, s(12)=39 by
    J. Harder, "An Answer to the Bose–Nelson Sorting Problem for 11 and 12
    Channels" (2020/22). Size optimality for n>=13 is OPEN.
  • Depth optimality known for n<=17: classical to n=10; 11<=n<=16 by
    Bundala & Závodný (2014); n=17 by Codish, Cruz-Filipe, Ehlers, Müller &
    Schneider-Kamp (2015), "Sorting Networks: to the End and Back Again",
    https://arxiv.org/abs/1507.01428. n>=18 OPEN.
  • n=16 best-known size 60: D. Bert Dobbelaere's compiled tables / Knuth.
`);
process.exit(fail === 0 ? 0 : 1);
