#!/usr/bin/env node
// verify.mjs — the committed, offline, reproducible check for
// "How Many Colors Does the Plane Need?" (the Hadwiger–Nelson stratum,
// /strata/coloring-the-plane/).
//
// The page demonstrates the two known walls of the chromatic number of the
// plane, 4 ≤ χ ≤ 7 (de Grey 2018: 5 ≤ χ ≤ 7), live in the reader's browser.
// This file re-proves the same two bounds from scratch, with no browser and no
// dependencies, so the claim does not rest on the page's say-so. Run:
//
//     node research/coloring-the-plane/verify.mjs
//
// Every assertion prints PASS/FAIL; the process exits nonzero if any fails.
//
// LOWER BOUND  χ ≥ 4 — the Moser spindle (Leo & William Moser, 1961):
//   • the exact coordinates the page draws give 11 unit-distance edges, and
//     exactly those 11 pairs (of the 21) are at distance 1 — a faithful
//     unit-distance graph;
//   • those coordinates match an independent first-principles construction
//     (two rhombi of unit equilateral triangles sharing the apex A, rotated by
//     θ with sin(θ/2) = 1/(2√3) so the far tips B1,B2 come to unit distance);
//   • exhaustive enumeration of all 3⁷ = 2187 three-colorings yields ZERO
//     proper ones (χ(spindle) ≥ 4); a proper 4-coloring exists (χ = 4);
//   • the spindle is 4-edge-critical: deleting any one of the 11 edges admits
//     a proper 3-coloring.
//   Because the plane contains a congruent copy of the spindle anywhere, χ ≥ 4.
//
// UPPER BOUND  χ ≤ 7 — Isbell's 7-coloring (John Isbell, 1950):
//   • the plane is tiled by regular hexagons of circumradius Rh = 0.46
//     (diameter 0.92 < 1), colored by (a − 2b) mod 7 over the hex lattice;
//   • within one tile every two points are < 1 apart (diameter 0.92);
//   • over a patch, EVERY pair of distinct same-colored hexagons has minimum
//     region-to-region distance > 1 (computed as an exact convex-polygon
//     distance) — so no two same-colored points are ever exactly 1 apart.
//   Coloring each plane point by its containing tile is therefore a proper
//   coloring with 7 colors, so χ ≤ 7.
//
// What stays open is genuinely open and is NOT claimed here: which of 5, 6, 7
// is the true value of χ. This verifier checks the two BOUNDS only.

const EPS = 1e-9;
let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  (cond ? (pass++) : (fail++));
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  —  ' + detail : ''}`);
}
const approx = (a, b, t = 1e-6) => Math.abs(a - b) <= t;

// ───────────────────────── geometry helpers ─────────────────────────
const dist = (p, q) => Math.hypot(p[0] - q[0], p[1] - q[1]);

// minimum distance between two convex polygons (vertex lists, CCW), assuming
// they do not overlap: min over all edge–edge segment distances. Exact.
function segSegDist(a, b, c, d) {
  // distance between segments ab and cd (no intersection test needed here:
  // the hexagons are disjoint, so the closest approach is between boundaries)
  const ptSeg = (p, u, v) => {
    const vx = v[0] - u[0], vy = v[1] - u[1];
    const L2 = vx * vx + vy * vy;
    let t = L2 === 0 ? 0 : ((p[0] - u[0]) * vx + (p[1] - u[1]) * vy) / L2;
    t = Math.max(0, Math.min(1, t));
    return Math.hypot(p[0] - (u[0] + t * vx), p[1] - (u[1] + t * vy));
  };
  return Math.min(
    ptSeg(a, c, d), ptSeg(b, c, d), ptSeg(c, a, b), ptSeg(d, a, b)
  );
}
function polyPolyDist(P, Q) {
  let m = Infinity;
  for (let i = 0; i < P.length; i++) {
    const a = P[i], b = P[(i + 1) % P.length];
    for (let j = 0; j < Q.length; j++) {
      const c = Q[j], d = Q[(j + 1) % Q.length];
      m = Math.min(m, segSegDist(a, b, c, d));
    }
  }
  return m;
}

// ═══════════════════════ PART 1 — the Moser spindle (χ ≥ 4) ═══════════════════════
console.log('\n── Lower bound: the Moser spindle (χ ≥ 4) ──');

// (a) the exact coordinates the page renders (public/strata/coloring-the-plane/index.html)
const V = {
  A:  [0, 0],
  P1: [0.9734937649, 0.2287135539],
  Q1: [0.6848186303, -0.7287135539],
  B1: [1.6583123952, -0.5],
  P2: [0.6848186303, 0.7287135539],
  Q2: [0.9734937649, -0.2287135539],
  B2: [1.6583123952, 0.5],
};
const names = Object.keys(V);
const E = [
  ['A', 'P1'], ['A', 'Q1'], ['A', 'P2'], ['A', 'Q2'], ['P1', 'Q1'],
  ['P1', 'B1'], ['Q1', 'B1'], ['B1', 'B2'], ['P2', 'Q2'], ['P2', 'B2'], ['Q2', 'B2'],
];

check('spindle has 7 vertices', names.length === 7, `${names.length}`);
check('spindle has 11 edges', E.length === 11, `${E.length}`);

// every listed edge is a unit distance
let edgeMaxErr = 0;
for (const [u, w] of E) edgeMaxErr = Math.max(edgeMaxErr, Math.abs(dist(V[u], V[w]) - 1));
check('all 11 edges are length 1', edgeMaxErr < 1e-6, `max |len−1| = ${edgeMaxErr.toExponential(2)}`);

// exactly those 11 pairs (of 21) are at distance 1 — a faithful unit-distance graph
const edgeSet = new Set(E.map(([u, w]) => [u, w].sort().join('-')));
let unitPairs = 0, spuriousUnit = [];
for (let i = 0; i < 7; i++) for (let j = i + 1; j < 7; j++) {
  const u = names[i], w = names[j];
  if (Math.abs(dist(V[u], V[w]) - 1) < 1e-6) {
    unitPairs++;
    if (!edgeSet.has([u, w].sort().join('-'))) spuriousUnit.push(`${u}-${w}`);
  }
}
check('exactly 11 of the 21 vertex pairs are unit-distance', unitPairs === 11, `${unitPairs}`);
check('no unit-distance pair is missing from the edge list', spuriousUnit.length === 0,
  spuriousUnit.length ? spuriousUnit.join(',') : 'none');

// the two long diagonals A–B1, A–B2 are √3 (two unit triangles per rhombus)
check('long diagonal A–B1 = √3', approx(dist(V.A, V.B1), Math.sqrt(3)), dist(V.A, V.B1).toFixed(10));
check('long diagonal A–B2 = √3', approx(dist(V.A, V.B2), Math.sqrt(3)), dist(V.A, V.B2).toFixed(10));

// (b) independent first-principles construction, cross-checked against the page coords.
// Two rhombi share apex A=(0,0); each far tip sits at radius √3; the rhombi are
// rotated so the two far tips are unit-distant: 1 = 2·√3·sin(θ/2) ⇒ sin(θ/2)=1/(2√3).
const half = Math.asin(1 / (2 * Math.sqrt(3)));      // θ/2
function rhombus(phi) {                                // far tip at angle phi
  const r3 = Math.sqrt(3);
  const tip = [r3 * Math.cos(phi), r3 * Math.sin(phi)];
  const mid = [tip[0] / 2, tip[1] / 2];                // |A–tip|=√3 ⇒ midpoint at √3/2
  const n = [-Math.sin(phi), Math.cos(phi)];           // unit normal to A–tip
  const off = 0.5;                                      // √(1 − (√3/2)²) = 1/2
  const s1 = [mid[0] + off * n[0], mid[1] + off * n[1]];
  const s2 = [mid[0] - off * n[0], mid[1] - off * n[1]];
  return { tip, s1, s2 };
}
const r1 = rhombus(-half), r2 = rhombus(+half);
// match constructed points to the page's by nearest-distance and confirm < 1e-6
const constructed = [[0, 0], r1.tip, r1.s1, r1.s2, r2.tip, r2.s1, r2.s2];
let maxMatch = 0;
for (const cp of constructed) {
  let best = Infinity;
  for (const n of names) best = Math.min(best, dist(cp, V[n]));
  maxMatch = Math.max(maxMatch, best);
}
check('page coordinates match the first-principles construction', maxMatch < 1e-6,
  `max nearest-point gap = ${maxMatch.toExponential(2)}`);
check('far tips B1,B2 are unit-distant in the construction',
  approx(dist(r1.tip, r2.tip), 1), dist(r1.tip, r2.tip).toFixed(10));

// (c) exhaustive coloring — the same enumeration the browser runs, offline.
function properColorings(k) {
  const idx = Object.fromEntries(names.map((n, i) => [n, i]));
  const total = k ** 7;
  let proper = 0, witness = null;
  const a = new Array(7);
  for (let code = 0; code < total; code++) {
    let x = code;
    for (let i = 0; i < 7; i++) { a[i] = x % k; x = (x - a[i]) / k; }
    let ok = true;
    for (const [u, w] of E) if (a[idx[u]] === a[idx[w]]) { ok = false; break; }
    if (ok) { proper++; if (!witness) witness = a.slice(); }
  }
  return { proper, witness };
}
const c3 = properColorings(3);
check('all 3⁷ = 2187 three-colorings enumerated: ZERO proper ⇒ χ ≥ 4',
  c3.proper === 0, `proper 3-colorings = ${c3.proper}`);
const c4 = properColorings(4);
check('a proper 4-coloring exists ⇒ χ(spindle) = 4', c4.proper > 0,
  `proper 4-colorings = ${c4.proper}`);

// (d) 4-edge-criticality — delete any one edge and 3 colors return.
function properExistsWithout(removeIdx, k = 3) {
  const idx = Object.fromEntries(names.map((n, i) => [n, i]));
  const sub = E.filter((_, i) => i !== removeIdx);
  const total = k ** 7, a = new Array(7);
  for (let code = 0; code < total; code++) {
    let x = code;
    for (let i = 0; i < 7; i++) { a[i] = x % k; x = (x - a[i]) / k; }
    let ok = true;
    for (const [u, w] of sub) if (a[idx[u]] === a[idx[w]]) { ok = false; break; }
    if (ok) return true;
  }
  return false;
}
let critical = true, badEdge = '';
for (let i = 0; i < E.length; i++) {
  if (!properExistsWithout(i)) { critical = false; badEdge = E[i].join('-'); break; }
}
check('4-edge-critical: removing any single edge admits a proper 3-coloring',
  critical, critical ? 'all 11 edges' : `failed at ${badEdge}`);

// ═══════════════════════ PART 2 — Isbell's 7-coloring (χ ≤ 7) ═══════════════════════
console.log("\n── Upper bound: Isbell's 7-coloring (χ ≤ 7) ──");

const Rh = 0.46;                          // hexagon circumradius (matches the page)
const s = Rh * Math.sqrt(3);              // adjacent-centre spacing
const e1 = [s, 0], e2 = [s * 0.5, s * Math.sqrt(3) / 2];
const colorOf = (a, b) => (((a - 2 * b) % 7) + 7) % 7;
const centre = (a, b) => [a * e1[0] + b * e2[0], a * e1[1] + b * e2[1]];
function hexPoly(c) {                      // 6 vertices, same orientation as the page (apex up)
  const v = [];
  for (let k = 0; k < 6; k++) {
    const ang = Math.PI / 2 + k * Math.PI / 3;
    v.push([c[0] + Rh * Math.cos(ang), c[1] + Rh * Math.sin(ang)]);
  }
  return v;
}

// (a) within-tile: diameter = 2·Rh < 1
const diameter = 2 * Rh;
check('hexagon diameter < 1 (two points in one tile are never unit-apart)',
  diameter < 1 - 1e-9, `diameter = ${diameter}`);

// (b) the coloring is a proper 7-coloring of the hex lattice in the abstract sense:
//     adjacent hexagons (the 6 neighbours) all get distinct colors from the centre.
const nbrs = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, -1], [-1, 1]];
let adjOk = true;
for (const [da, db] of nbrs) if (colorOf(da, db) === colorOf(0, 0)) adjOk = false;
check('the 6 hex-neighbours of any tile all differ in color from it', adjOk);

// (c) the decisive metric claim: over a patch, the minimum region-to-region
//     distance between any two DISTINCT same-colored hexagons exceeds 1.
const R = 12;                              // patch radius in lattice steps
const c0 = centre(0, 0), p0 = hexPoly(c0), col0 = colorOf(0, 0);
let minSame = Infinity, argmin = null;
for (let a = -R; a <= R; a++) for (let b = -R; b <= R; b++) {
  if (a === 0 && b === 0) continue;
  if (colorOf(a, b) !== col0) continue;    // same color as the origin tile
  const d = polyPolyDist(p0, hexPoly(centre(a, b)));
  if (d < minSame) { minSame = d; argmin = [a, b]; }
}
check('min distance between two same-colored tiles > 1 ⇒ no monochromatic unit pair',
  minSame > 1 + 1e-9,
  `min = ${minSame.toFixed(6)} at lattice step (${argmin})`);

// (d) and confirm it holds for EVERY color class, not just the origin's, across the patch.
let globalMinSame = Infinity;
const cells = [];
for (let a = -R; a <= R; a++) for (let b = -R; b <= R; b++) cells.push([a, b]);
// only need to compare the origin tile against its color class (lattice is transitive),
// but we sanity-check a second color class explicitly:
const ref = [1, 0], colRef = colorOf(...ref), pRef = hexPoly(centre(...ref));
for (const [a, b] of cells) {
  if (a === ref[0] && b === ref[1]) continue;
  if (colorOf(a, b) !== colRef) continue;
  globalMinSame = Math.min(globalMinSame, polyPolyDist(pRef, hexPoly(centre(a, b))));
}
check('same separation holds for a second color class (lattice transitivity)',
  globalMinSame > 1 + 1e-9, `min = ${globalMinSame.toFixed(6)}`);

// same-color centre spacing is s·√7 (the index-7 sublattice), a structural cross-check
check('nearest same-color centres sit at s·√7',
  approx(dist(c0, centre(...argmin)), s * Math.sqrt(7)),
  `${dist(c0, centre(...argmin)).toFixed(6)} vs ${(s * Math.sqrt(7)).toFixed(6)}`);

// ───────────────────────── summary ─────────────────────────
console.log(`\n${'─'.repeat(60)}`);
console.log(`χ ≥ 4 (Moser spindle) and χ ≤ 7 (Isbell): ${pass}/${pass + fail} checks passed.`);
console.log('Open, and not claimed here: which of 5, 6, 7 is χ.');
if (fail > 0) { console.log(`\n${fail} FAILED.`); process.exit(1); }
console.log('All checks passed.');
