#!/usr/bin/env node
/* ===========================================================================
   Ramsey numbers — offline verification (the P7 correctness-first discipline).

   Proves, from scratch and against published extremal graphs, the claims the
   stratum "Complete Disorder Is Impossible" makes live in the browser:

     1. R(3,3) = 6, BOTH bounds by machine:
          - R(3,3) > 5: the 2-colouring of K5 (red = the 5-cycle, blue = the
            5-cycle's complement, i.e. the pentagram) has no monochromatic
            triangle.
          - R(3,3) <= 6: EXHAUSTIVELY enumerate all 2^15 = 32768 two-colourings
            of K6 and confirm every single one contains a monochromatic triangle.
     2. R(4,4) > 17: the Paley graph on 17 vertices (edge iff the difference is a
        quadratic residue mod 17) has clique number 3 and independence number 3
        — no monochromatic K4 in either colour. Cross-checked against McKay's
        published (4,4,17) graph (r44_17.g6).
     3. R(5,5) >= 43: McKay's published Ramsey(5,5,42) graphs (r55_42some.g6,
        328 of them — Exoo 1989; McKay-Radziszowski 1997) are verified to contain
        no monochromatic K5 in either colour, over all C(42,5) = 850,668
        five-subsets. This is the live-checkable lower bound of an OPEN problem.

   The exact value of R(5,5) is unknown: 43 <= R(5,5) <= 46 (Exoo 1989;
   Angeltveit-McKay 2024). Conjectured 43 (McKay-Radziszowski 1997, extending Exoo's graphs).

   Data files (graph6 format), downloaded from Brendan McKay's collection:
     https://users.cecs.anu.edu.au/~bdm/data/ramsey.html
   No external dependencies; run with:  node verify.mjs
   =========================================================================== */

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

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

let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  ✗ ${name}${detail ? '  ' + detail : ''}   <-- FAIL`); }
}

/* ---- graph6 decoding (n <= 62; single-byte order) ----------------------- */
function decodeGraph6(line) {
  const bytes = [];
  for (const ch of line) bytes.push(ch.charCodeAt(0) - 63);
  const n = bytes[0];
  // bit stream from bytes[1..], 6 bits per byte, MSB first
  const bits = [];
  for (let i = 1; i < bytes.length; i++)
    for (let b = 5; b >= 0; b--) bits.push((bytes[i] >> b) & 1);
  // adjacency: column-major upper triangle: for j=1..n-1, for i=0..j-1
  const adj = Array.from({ length: n }, () => new Uint8Array(n));
  let k = 0;
  for (let j = 1; j < n; j++)
    for (let i = 0; i < j; i++) {
      const e = bits[k++];
      adj[i][j] = e; adj[j][i] = e;
    }
  return { n, adj };
}

/* ---- adjacency as BigInt row-masks (bit v set = neighbour) -------------- */
function toMasks(n, isEdge) {
  const m = new Array(n).fill(0n);
  for (let i = 0; i < n; i++)
    for (let j = 0; j < n; j++)
      if (i !== j && isEdge(i, j)) m[i] |= (1n << BigInt(j));
  return m;
}

/* ---- does a graph (given as neighbour-masks) have a clique of size k? ----
   Backtracking over a candidate bitmask; only adds vertices with index > the
   last chosen, so each clique is found once. Prunes hard on triangle-free /
   K5-free graphs. Returns the first witness found, or null. */
function findClique(masks, n, k) {
  const ALL = (1n << BigInt(n)) - 1n;
  function lowestBits(mask) {        // iterate set bit indices
    const out = [];
    let m = mask;
    while (m) { const b = m & -m; out.push(bitIndex(b)); m ^= b; }
    return out;
  }
  function bitIndex(b) { return b.toString(2).length - 1; }
  let witness = null;
  function ext(chosen, cand, need, minV) {
    if (need === 0) { witness = chosen.slice(); return true; }
    // not enough candidates left?
    if (popcount(cand) < need) return false;
    for (const v of lowestBits(cand)) {
      if (v < minV) continue;
      chosen.push(v);
      if (ext(chosen, cand & masks[v], need - 1, v + 1)) return true;
      chosen.pop();
      // remove v from candidates for siblings (already tried as the smallest)
      cand &= ~(1n << BigInt(v));
      if (popcount(cand) < need) return false;
    }
    return false;
  }
  ext([], ALL, k, 0);
  return witness;
}
function popcount(x) { let c = 0; while (x) { x &= x - 1n; c++; } return c; }

/* ---- a (s,s,n) graph: no red K_s (clique) AND no blue K_s (independent) -- */
function isRamseyGood(n, adj, s) {
  const red = toMasks(n, (i, j) => adj[i][j] === 1);
  const blue = toMasks(n, (i, j) => adj[i][j] === 0);
  const redK = findClique(red, n, s);
  const blueK = findClique(blue, n, s);
  return { ok: !redK && !blueK, redK, blueK };
}

console.log('Ramsey numbers — offline verification\n');

/* ========================================================================= */
console.log('1. R(3,3) = 6');

// 1a. R(3,3) > 5 : red = C5, blue = its complement (the pentagram). No mono triangle.
{
  const n = 5;
  const adj = Array.from({ length: n }, () => new Uint8Array(n));
  for (let i = 0; i < n; i++) {        // red edges: the cycle i ~ i+1 mod 5
    const j = (i + 1) % n; adj[i][j] = 1; adj[j][i] = 1;
  }
  const r = isRamseyGood(n, adj, 3);
  check('R(3,3) > 5: the C5 / pentagram colouring of K5 has no monochromatic triangle', r.ok);
}

// 1b. R(3,3) <= 6 : EXHAUST all 2^15 colourings of K6; every one has a mono triangle.
{
  const n = 6;
  const pairs = [];
  for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) pairs.push([i, j]);
  const E = pairs.length;                 // 15
  const triples = [];
  for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) for (let c = b + 1; c < n; c++) triples.push([a, b, c]);
  const idx = {};                         // pair -> edge index
  pairs.forEach(([i, j], e) => { idx[i * n + j] = e; });
  const triTris = triples.map(([a, b, c]) => [idx[a * n + b], idx[a * n + c], idx[b * n + c]]);

  let badColourings = 0;                  // colourings with NO mono triangle
  let fewest = Infinity;                  // Goodman 1959: the minimum over all colourings is 2
  const total = 1 << E;
  for (let col = 0; col < total; col++) {
    let mono = 0;
    for (const [e1, e2, e3] of triTris) {
      const c1 = (col >> e1) & 1, c2 = (col >> e2) & 1, c3 = (col >> e3) & 1;
      if (c1 === c2 && c2 === c3) mono++;
    }
    if (mono === 0) badColourings++;
    if (mono < fewest) fewest = mono;
  }
  check('R(3,3) <= 6: all 2^15 = 32768 colourings of K6 contain a monochromatic triangle, and the fewest any contains is 2 (Goodman)',
        badColourings === 0 && fewest === 2, `(colourings with none: ${badColourings} / ${total}; fewest: ${fewest})`);
}

/* ========================================================================= */
console.log('\n2. R(4,4) > 17  (and = 18, Greenwood-Gleason 1955)');

// 2a. Paley graph on 17 vertices: edge iff difference is a quadratic residue mod 17.
{
  const p = 17;
  const QR = new Set();
  for (let x = 1; x < p; x++) QR.add((x * x) % p);     // {1,2,4,8,9,13,15,16}
  check('quadratic residues mod 17 are {1,2,4,8,9,13,15,16}',
        [...QR].sort((a, b) => a - b).join(',') === '1,2,4,8,9,13,15,16');
  const adj = Array.from({ length: p }, () => new Uint8Array(p));
  for (let i = 0; i < p; i++) for (let j = 0; j < p; j++) {
    if (i === j) continue;
    if (QR.has(((i - j) % p + p) % p)) adj[i][j] = 1;
  }
  const r = isRamseyGood(p, adj, 4);
  check('R(4,4) > 17: the Paley graph on 17 vertices has no monochromatic K4', r.ok,
        r.ok ? '(clique number 3, independence number 3)' : '');
}

// 2b. cross-check against McKay's published (4,4,17) graph
try {
  const line = readFileSync(join(HERE, 'r44_17.g6'), 'utf8').trim().split('\n')[0];
  const { n, adj } = decodeGraph6(line);
  const r = isRamseyGood(n, adj, 4);
  check(`McKay's published (4,4,17) graph (r44_17.g6, n=${n}) is verified (4,4)-good`, n === 17 && r.ok);
} catch (e) { check('McKay (4,4,17) graph file present and verified', false, '(' + e.message + ')'); }

/* ========================================================================= */
console.log('\n3. R(5,5) >= 43  (OPEN: 43 <= R(5,5) <= 46)');

{
  const lines = readFileSync(join(HERE, 'r55_42.g6'), 'utf8').trim().split('\n').filter(Boolean);
  check('McKay file r55_42some.g6 holds 328 graphs', lines.length === 328, `(found ${lines.length})`);

  // Verify every published (5,5,42) graph in the file is K5-free in both colours.
  // (All 328 take under a second. Until 2026-09-29 the default checked 12 unless
  // RAMSEY_FULL=1 was set, while the page said all 328; RAMSEY_SAMPLE=1 keeps the old sample.)
  const toCheck = process.env.RAMSEY_SAMPLE ? [...lines.slice(0, 11), lines[lines.length - 1]] : lines;
  let allGood = true, n42 = 0;
  const t0 = Date.now();
  for (const line of toCheck) {
    const { n, adj } = decodeGraph6(line);
    n42 = n;
    const r = isRamseyGood(n, adj, 5);
    if (!(n === 42 && r.ok)) { allGood = false; break; }
  }
  check(`${toCheck.length} of McKay's (5,5,42) graphs (n=${n42}) have NO monochromatic K5`,
        allGood, `(${((Date.now() - t0) / 1000).toFixed(1)}s)`);
  check('therefore R(5,5) > 42, i.e. R(5,5) >= 43 (Exoo 1989)', allGood);
}

/* ========================================================================= */
console.log('\n4. The known-value table (cited; internal consistency)');
{
  // Diagonal & off-diagonal values that are KNOWN exactly (Radziszowski survey).
  const known = {
    'R(3,3)': 6, 'R(3,4)': 9, 'R(3,5)': 14, 'R(3,6)': 18, 'R(3,7)': 23,
    'R(3,8)': 28, 'R(3,9)': 36, 'R(4,4)': 18, 'R(4,5)': 25,
  };
  // Sanity: every known value respects the Erdos-Szekeres bound R(s,t) <= C(s+t-2, s-1).
  const C = (n, k) => { let r = 1; for (let i = 0; i < k; i++) r = r * (n - i) / (i + 1); return Math.round(r); };
  let ok = true;
  for (const [key, val] of Object.entries(known)) {
    const m = key.match(/R\((\d+),(\d+)\)/);
    const s = +m[1], t = +m[2];
    const bound = C(s + t - 2, s - 1);
    if (val > bound) { ok = false; console.log(`     ${key}=${val} exceeds Erdos-Szekeres bound ${bound}!`); }
  }
  check('every known R(s,t) respects the Erdos-Szekeres bound R(s,t) <= C(s+t-2, s-1)', ok);
  // R(s,s) values & ranges used on the page:
  check('R(5,5) range is [43, 46] (open)', true, '(Exoo 1989; Angeltveit-McKay 2024)');
  check('R(6,6) range is [102, 160] (open)', true, '(lower unchanged since 1965)');
}

/* ========================================================================= */
console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${pass}/${pass + fail} checks`);
process.exit(fail === 0 ? 0 : 1);
