// verify.mjs — the verified core of "Two Points the Same" (Borsuk–Ulam)
//
// The claim the stratum makes: at every instant there exist two ANTIPODAL points on
// Earth's surface with the same temperature AND the same barometric pressure — and
// this is forced, not lucky. It is the Borsuk–Ulam theorem (Borsuk 1933): every
// continuous map f : S^n → R^n sends some antipodal pair to the same value,
// f(p) = f(−p). For n = 2, the two coordinates are temperature and pressure.
//
// This file proves/checks the pieces that CAN be checked, and is explicit about the
// one thing that cannot be reduced to arithmetic (the topological non-existence of an
// antipodal map S^2 → S^1, which the page states and cites rather than re-derives).
//
//   ENGINE 1 — 1-D Borsuk–Ulam (the equator). For continuous f : S^1 → R the
//     auxiliary g(θ) = f(θ) − f(θ+π) is ODD under the half-turn: g(θ+π) = −g(θ).
//     An odd continuous function takes opposite signs at θ and θ+π, so by the
//     Intermediate Value Theorem it has a zero — an antipodal pair with equal value.
//     Checked on thousands of random continuous fields by locating the zero.
//
//   ENGINE 2 — Tucker's lemma in 1-D (the combinatorial heart, EXHAUSTIVE). Discrete
//     Borsuk–Ulam: any antipodally-symmetric ±1 labeling of an even cycle has a
//     "complementary edge" (+1 adjacent to −1). Verified over ALL such labelings for
//     several ring sizes — there is no escape, exhaustively.
//
//   ENGINE 3 — Tucker's lemma in 2-D (a triangulated antipodal disk, by search).
//     Labels in {±1,±2}, antipodal on the boundary ⇒ a complementary edge always
//     exists. Checked over many random boundary-antipodal labelings; and the
//     CONTRAPOSITIVE — that you cannot color the disk to avoid one — is what the
//     page's "try to escape" instrument lets you fail at by hand.
//
//   ENGINE 4 — Ham-sandwich (a corollary), exact small instance: two finite point
//     sets in the plane simultaneously bisected by one straight line. Found and
//     checked in exact integer counts.
//
//   ENGINE 5 — the 2-D existence FOUND numerically (the page's demo engine): smooth
//     temperature & pressure fields on the sphere from low-degree spherical harmonics,
//     and an antipodal pair driven to T(p)=T(−p) AND P(p)=P(−p) to machine residual.
//     Existence is GUARANTEED by the theorem; the locating is numerics.
//
// Run: node research/borsuk-ulam/verify.mjs

import { strict as assert } from 'node:assert';

let PASS = 0, FAIL = 0;
function ok(cond, msg) { if (cond) { PASS++; console.log('  ✓ ' + msg); } else { FAIL++; console.log('  ✗ ' + msg); } }

// ---------- a small deterministic PRNG so the run is reproducible ----------
function mulberry32(a) { 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; }; }
const rnd = mulberry32(0x5eed);

// =====================================================================
// ENGINE 1 — 1-D Borsuk–Ulam on the circle (equal temperature on the equator)
// =====================================================================
console.log('\nENGINE 1 — 1-D Borsuk–Ulam: an antipodal pair on any loop with equal value\n');

// a random continuous, 2π-periodic field as a Fourier sum (so f is genuinely smooth)
function randomLoopField() {
  const K = 6, a = [], b = [];
  for (let k = 1; k <= K; k++) { a.push(2 * rnd() - 1); b.push(2 * rnd() - 1); }
  const c0 = 4 * rnd() - 2;
  return (theta) => {
    let s = c0;
    for (let k = 1; k <= K; k++) { s += a[k - 1] * Math.cos(k * theta) + b[k - 1] * Math.sin(k * theta); }
    return s;
  };
}

let antisymOK = true, zeroFound = 0, trials1 = 4000;
let worstResidual = 0;
for (let t = 0; t < trials1; t++) {
  const f = randomLoopField();
  const g = (th) => f(th) - f(th + Math.PI);
  // (a) the mechanism: g is odd under the half-turn, g(θ+π) = −g(θ), to machine precision
  for (let s = 0; s < 5; s++) {
    const th = 2 * Math.PI * rnd();
    if (Math.abs(g(th + Math.PI) + g(th)) > 1e-9) antisymOK = false;
  }
  // (b) IVT: g(0) and g(π) = −g(0) bracket a sign change on [0, π]; bisect to the zero
  let lo = 0, hi = Math.PI, glo = g(lo), ghi = g(hi);
  if (glo === 0) { zeroFound++; continue; }
  // glo and ghi must have opposite signs (ghi = -glo)
  if (Math.sign(glo) === Math.sign(ghi)) continue; // (cannot happen; guarded below)
  for (let it = 0; it < 80; it++) {
    const mid = 0.5 * (lo + hi), gm = g(mid);
    if (Math.sign(gm) === Math.sign(glo)) { lo = mid; glo = gm; } else { hi = mid; ghi = gm; }
  }
  const thStar = 0.5 * (lo + hi);
  const residual = Math.abs(f(thStar) - f(thStar + Math.PI));
  worstResidual = Math.max(worstResidual, residual);
  if (residual < 1e-9) zeroFound++;
}
ok(antisymOK, 'g(θ) = f(θ) − f(θ+π) is odd under the half-turn: g(θ+π) = −g(θ) exactly');
ok(zeroFound === trials1, `every one of ${trials1} random loops has an antipodal equal-value pair (worst residual ${worstResidual.toExponential(2)})`);

// =====================================================================
// ENGINE 2 — Tucker's lemma in 1-D, EXHAUSTIVE (the discrete IVT, no escape)
// =====================================================================
console.log('\nENGINE 2 — Tucker 1-D: every antipodal ±1 labeling of an even ring has a complementary edge\n');

// vertices 0..2n-1 on a cycle; antipode of i is (i+n) mod 2n. Antipodal labeling:
// label(i+n) = -label(i). A "complementary edge" is adjacent vertices (i, i+1) with
// labels {+1, -1}. Tucker (n=1 dim): such an edge MUST exist. Check ALL labelings.
function tucker1DExhaustive(n) {
  const N = 2 * n;
  let total = 0, withComplementary = 0;
  // a labeling is fixed by the first n vertices' signs (the other n are forced antipodal)
  for (let mask = 0; mask < (1 << n); mask++) {
    const lab = new Array(N);
    for (let i = 0; i < n; i++) { const s = (mask >> i) & 1 ? 1 : -1; lab[i] = s; lab[i + n] = -s; }
    total++;
    let hasComp = false;
    for (let i = 0; i < N; i++) {
      const j = (i + 1) % N;
      if (lab[i] === -lab[j]) { hasComp = true; break; } // {+1,-1} adjacent
    }
    if (hasComp) withComplementary++;
  }
  return { total, withComplementary };
}
for (const n of [2, 3, 4, 5, 6, 8]) {
  const r = tucker1DExhaustive(n);
  ok(r.withComplementary === r.total, `ring of ${2 * n}: all ${r.total} antipodal ±1 labelings have a +/− edge (no escape)`);
}

// =====================================================================
// ENGINE 3 — Tucker's lemma in 2-D, by search (labels ±1,±2 on a symmetric disk)
// =====================================================================
console.log('\nENGINE 3 — Tucker 2-D: antipodal boundary labeling forces a complementary edge\n');

// An antipodally symmetric triangulated disk: a regular m-gon boundary (m even) with a
// center vertex, triangulated as a fan. Antipode of boundary vertex k is k+m/2; the
// center is interior (no boundary constraint applies). Tucker (combinatorial
// Borsuk–Ulam, dim 2): any labeling in {±1,±2} that is antipodal on the boundary
// contains an edge labeled {+1,−1} or {+2,−2}. The label space here is small, so we
// enumerate EVERY antipodal-boundary labeling exhaustively — the half-boundary has
// 4^(m/2) choices and the free center has 4 — and confirm none escapes.
function tucker2DDiskExhaustive(m) {
  const half = m / 2, VALS = [1, 2, -1, -2];
  const edges = [];
  for (let k = 0; k < m; k++) edges.push([k, (k + 1) % m]);  // boundary cycle
  for (let k = 0; k < m; k++) edges.push([m, k]);            // spokes to center (index m)
  let total = 0, withComp = 0;
  const lab = new Array(m + 1);
  function recurse(k) {
    if (k === half) {
      for (const c of VALS) {
        lab[m] = c; total++;
        let hasComp = false;
        for (const [a, b] of edges) { if (lab[a] === -lab[b]) { hasComp = true; break; } }
        if (hasComp) withComp++;
      }
      return;
    }
    for (const v of VALS) { lab[k] = v; lab[k + half] = -v; recurse(k + 1); }
  }
  recurse(0);
  return { total, withComp };
}
for (const m of [6, 8, 10, 12]) {
  const r = tucker2DDiskExhaustive(m);
  ok(r.withComp === r.total, `disk(${m}-gon + center): all ${r.total} antipodal-boundary labelings have a complementary edge (exhaustive)`);
}

// =====================================================================
// ENGINE 4 — Ham-sandwich corollary: one line bisects two point sets (exact)
// =====================================================================
console.log('\nENGINE 4 — Ham-sandwich: a single line halves two finite point sets at once\n');

// Discrete ham-sandwich in the plane: given a red set (|R| even) and a blue set
// (|B| even), there is a line with exactly |R|/2 red strictly on each side and |B|/2
// blue strictly on each side. We search the (finite) set of combinatorially-distinct
// directions/offsets — here a robust exact search over lines through pairs of points
// plus rotations — and verify exact integer balance. Done over random configurations.
function signedSide(px, py, ux, uy, ox, oy) {
  // sign of cross((u),(p-o)); >0 one side, <0 the other, 0 on the line
  return Math.sign(ux * (py - oy) - uy * (px - ox));
}
function bisectsBoth(R, B, ux, uy, ox, oy) {
  let rp = 0, rm = 0, bp = 0, bm = 0;
  for (const [x, y] of R) { const s = signedSide(x, y, ux, uy, ox, oy); if (s > 0) rp++; else if (s < 0) rm++; else return false; }
  for (const [x, y] of B) { const s = signedSide(x, y, ux, uy, ox, oy); if (s > 0) bp++; else if (s < 0) bm++; else return false; }
  return rp === rm && bp === bm;
}
function findHamSandwich(R, B) {
  const all = [...R, ...B];
  // candidate directions: perpendiculars to all point-pair directions (and a sweep)
  const dirs = [];
  for (let i = 0; i < all.length; i++) for (let j = i + 1; j < all.length; j++) {
    const dx = all[j][0] - all[i][0], dy = all[j][1] - all[i][1];
    dirs.push([dx, dy], [-dy, dx]);
  }
  for (let a = 0; a < 720; a++) { const t = a * Math.PI / 720; dirs.push([Math.cos(t), Math.sin(t)]); }
  for (const [ux, uy] of dirs) {
    // candidate offsets: midpoints between consecutive projections
    const proj = all.map(([x, y]) => ({ x, y, t: -uy * x + ux * y })).sort((p, q) => p.t - q.t);
    for (let k = 0; k < proj.length - 1; k++) {
      const mx = 0.5 * (proj[k].x + proj[k + 1].x), my = 0.5 * (proj[k].y + proj[k + 1].y);
      if (bisectsBoth(R, B, ux, uy, mx, my)) return { ux, uy, ox: mx, oy: my };
    }
  }
  return null;
}
let hamFound = 0, hamTrials = 300;
for (let t = 0; t < hamTrials; t++) {
  const nR = 2 * (1 + Math.floor(rnd() * 5)), nB = 2 * (1 + Math.floor(rnd() * 5));
  const R = [], B = [], used = new Set();
  function pt() { let x, y, key; do { x = Math.floor(rnd() * 200) - 100; y = Math.floor(rnd() * 200) - 100; key = x + ',' + y; } while (used.has(key)); used.add(key); return [x, y]; }
  for (let i = 0; i < nR; i++) R.push(pt());
  for (let i = 0; i < nB; i++) B.push(pt());
  const sol = findHamSandwich(R, B);
  if (sol && bisectsBoth(R, B, sol.ux, sol.uy, sol.ox, sol.oy)) hamFound++;
}
ok(hamFound === hamTrials, `a simultaneous bisecting line found for all ${hamTrials} random red/blue configurations`);

// =====================================================================
// ENGINE 5 — the page's demo engine: equal T AND P at an antipodal pair, found
// =====================================================================
console.log('\nENGINE 5 — smooth (T,P) fields on the sphere: an antipodal match driven to ~0 residual\n');

// point on S^2 from azimuth θ∈[0,2π), polar φ∈[0,π]
function sph(theta, phi) { const s = Math.sin(phi); return [s * Math.cos(theta), s * Math.sin(theta), Math.cos(phi)]; }
function antipode(theta, phi) { return [theta + Math.PI, Math.PI - phi]; } // (−x,−y,−z)

// a smooth field = sum of low-degree terms in the Cartesian coords of the unit vector
function randomField() {
  const c = []; for (let i = 0; i < 10; i++) c.push(2 * rnd() - 1);
  return ([x, y, z]) =>
    c[0] + c[1] * x + c[2] * y + c[3] * z +
    c[4] * x * y + c[5] * y * z + c[6] * z * x +
    c[7] * (x * x - y * y) + c[8] * (3 * z * z - 1) + c[9] * x * y * z;
}

function solveAntipodalMatch(T, P) {
  // we seek (θ,φ) with gT=T(p)-T(-p)=0 and gP=P(p)-P(-p)=0. Both odd ⇒ a zero exists.
  const G = (theta, phi) => {
    const p = sph(theta, phi), q = sph(...antipode(theta, phi));
    return [T(p) - T(q), P(p) - P(q)];
  };
  // multi-start Newton on the 2×2 system over the hemisphere of seeds
  const seeds = [];
  for (let i = 0; i < 12; i++) for (let j = 1; j < 12; j++) seeds.push([2 * Math.PI * i / 12, Math.PI * j / 12]);
  let best = Infinity, bestSol = null;
  for (let [th, ph] of seeds) {
    for (let it = 0; it < 60; it++) {
      const [g1, g2] = G(th, ph);
      const h = 1e-6;
      const [g1a] = G(th + h, ph), [g1b, , ] = G(th, ph + h);
      const [, g2a] = G(th + h, ph), [, g2b] = G(th, ph + h);
      const J11 = (G(th + h, ph)[0] - g1) / h, J12 = (G(th, ph + h)[0] - g1) / h;
      const J21 = (G(th + h, ph)[1] - g2) / h, J22 = (G(th, ph + h)[1] - g2) / h;
      const det = J11 * J22 - J12 * J21;
      if (Math.abs(det) < 1e-12) break;
      const dth = (J22 * g1 - J12 * g2) / det, dph = (-J21 * g1 + J11 * g2) / det;
      th -= dth; ph -= dph;
      if (!isFinite(th) || !isFinite(ph)) break;
      ph = Math.max(1e-4, Math.min(Math.PI - 1e-4, ph));
    }
    const [r1, r2] = G(th, ph); const res = Math.hypot(r1, r2);
    if (res < best) { best = res; bestSol = [th, ph]; }
    if (best < 1e-10) break;
  }
  return { residual: best, sol: bestSol };
}

let matchFound = 0, e5trials = 500, worst5 = 0;
for (let t = 0; t < e5trials; t++) {
  const T = randomField(), P = randomField();
  const { residual } = solveAntipodalMatch(T, P);
  worst5 = Math.max(worst5, residual);
  if (residual < 1e-7) matchFound++;
}
ok(matchFound === e5trials, `equal-T-and-P antipodal pair located on all ${e5trials} random smooth fields (worst residual ${worst5.toExponential(2)})`);

// a fixed, page-quoted instance so the stratum cites an exact number
{
  const T = randomField(), P = randomField();
  const { residual, sol } = solveAntipodalMatch(T, P);
  const thetaNorm = ((sol[0] % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
  ok(residual < 1e-9, `worked example: residual ${residual.toExponential(2)} at (θ,φ)=(${thetaNorm.toFixed(4)}, ${sol[1].toFixed(4)})`);
}

// =====================================================================
console.log(`\n${FAIL === 0 ? 'ALL CHECKS PASS' : 'SOME CHECKS FAILED'} — ${PASS}/${PASS + FAIL}\n`);
process.exit(FAIL === 0 ? 0 : 1);
