#!/usr/bin/env node
// The Three-Gap (Steinhaus / three-distance) theorem: finite offline checks.
//
// Claim under test: the arcs between consecutive distinct points {k*a},
// k = 0,...,N-1, have at most three lengths. When three lengths occur,
// the longest equals the sum of the other two.
//
// For a = num/den in lowest terms and N <= den, positions and gap lengths
// are exact BigInt multiples of 1/den. The exhaustive sweep covers
// 0 < num < den, 2 <= den <= 220, 1 <= N <= den; 4,000 seeded random
// cases extend that finite range. These checks are not a universal proof.
//
// The smallest gap, for N >= 2 distinct points, is the minimum scaled
// approximation error min_{1<=q<N} ||q*a||, not the fraction p/q itself.
// Each new distinct point splits a current largest gap; the maximum
// gap length cannot increase.
//
// The golden tests use the rational proxy F41/F42. Gap lengths are exact;
// their ratios use Number division and the phi-squared comparison allows
// 1e-9 tolerance. We sample 714 counts N=5,12,...,4996 and separately
// test 27 Fibonacci counts F4=3 through F30=832040. The mathematical
// golden-angle bound holds for all N, with two lengths at Fibonacci
// N >= 2 and a single full-turn gap at N=1.
//
// Run: node research/three-gap/verify.mjs
'use strict';

let PASS = 0, FAIL = 0;
const log = (ok, msg) => { (ok ? PASS++ : FAIL++); console.log((ok ? '  ok  ' : 'FAIL  ') + msg); };
const gcd = (a, b) => { a = BigInt(a); b = BigInt(b); while (b) { [a, b] = [b, a % b]; } return a < 0n ? -a : a; };
const norm = (q, M, D) => { let r = (BigInt(q) * M) % D; if (r < 0n) r += D; return r < D - r ? r : D - r; };

function positions(num, den, N) {
  const D = BigInt(den), M = BigInt(num);
  const p = new Array(N); let a = 0n;
  for (let k = 0; k < N; k++) { p[k] = a; a = (a + M) % D; }
  p.sort((x, y) => (x < y ? -1 : x > y ? 1 : 0));
  return p;
}
function gapList(num, den, N) {
  const p = positions(num, den, N), D = BigInt(den), g = new Array(N);
  for (let i = 0; i < N; i++) g[i] = (i + 1 < N ? p[i + 1] : p[0] + D) - p[i];
  return g;
}
function gapCounts(num, den, N) {
  const g = gapList(num, den, N), m = new Map();
  for (const x of g) { const k = x.toString(); m.set(k, (m.get(k) || 0) + 1); }
  return m;
}

// ---------- TEST 1: exhaustive finite grid, denominators 2 through 220 ----------
{
  let cases = 0, three = 0, two = 0, one = 0, maxDistinct = 0, violations = 0, sumViolations = 0;
  for (let den = 2; den <= 220; den++) {
    for (let num = 1; num < den; num++) {
      if (gcd(num, den) !== 1n) continue;
      for (let N = 1; N <= den; N++) {
        const g = gapCounts(num, den, N);
        const lens = [...g.keys()].map(BigInt).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
        cases++; maxDistinct = Math.max(maxDistinct, lens.length);
        if (lens.length > 3) violations++;
        if (lens.length === 3) { three++; if (lens[2] !== lens[0] + lens[1]) sumViolations++; }
        else if (lens.length === 2) two++; else one++;
        let s = 0n; for (const [k, c] of g) s += BigInt(k) * BigInt(c);
        if (s !== BigInt(den)) violations++;
      }
    }
  }
  console.log(`\n[1] exhaustive grid  a=num/den, 2≤den≤220, all coprime num, all 1≤N≤den`);
  console.log(`    ${cases.toLocaleString()} (a,N) cases checked exactly`);
  console.log(`    distinct gap lengths: max = ${maxDistinct}   (one:${one.toLocaleString()}  two:${two.toLocaleString()}  three:${three.toLocaleString()})`);
  log(maxDistinct <= 3 && violations === 0, `never more than three distinct gap lengths (and gaps always sum to the circle)`);
  log(sumViolations === 0, `with three lengths, the longest = sum of the two shorter (${three.toLocaleString()} cases, 0 violations)`);
}

// ---------- TEST 2: random large denominators (stress beyond the grid) ----------
{
  const rng = (s) => { s = s >>> 0; return () => (s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32; };
  const r = rng(20260621);
  let cases = 0, bad = 0, badsum = 0;
  for (let t = 0; t < 4000; t++) {
    const den = 1000 + Math.floor(r() * 9_000_000);
    let num = 1 + Math.floor(r() * (den - 1));
    while (gcd(num, den) !== 1n) num = 1 + Math.floor(r() * (den - 1));
    const N = 1 + Math.floor(r() * Math.min(den, 50000));
    const g = gapCounts(num, den, N);
    const lens = [...g.keys()].map(BigInt).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
    cases++;
    if (lens.length > 3) bad++;
    if (lens.length === 3 && lens[2] !== lens[0] + lens[1]) badsum++;
  }
  console.log(`\n[2] random a=num/den, den up to ~9e6, N up to 5e4`);
  log(bad === 0 && badsum === 0, `${cases.toLocaleString()} random cases: never >3 lengths, sum law never broken`);
}

// ---------- TEST 3: the smallest gap is the minimum scaled approximation error ----------
{
  let ok = 0, tot = 0;
  for (let den = 2; den <= 160; den++) for (let num = 1; num < den; num++) {
    if (gcd(num, den) !== 1n) continue;
    const D = BigInt(den), M = BigInt(num);
    for (let N = 2; N <= den; N++) {
      const minGap = gapList(num, den, N).reduce((a, b) => (b < a ? b : a));
      let best = D; for (let q = 1; q < N; q++) { const d = norm(q, M, D); if (d < best) best = d; }
      tot++; if (minGap === best) ok++;
    }
  }
  console.log(`\n[3] smallest gap = min_{1≤q<N} ‖q·a‖  (the minimum scaled approximation error)`);
  log(ok === tot, `the smallest gap equals the minimum scaled error ||q*a|| for 1<=q<N  (${ok.toLocaleString()}/${tot.toLocaleString()})`);
}

// ---------- TEST 4: the dynamic — a new point splits a largest gap, never grows it ----------
{
  let checks = 0, landedInBiggest = 0, neverGrows = 0;
  for (const [num, den] of [[233, 377], [355, 113113], [44, 197], [9999, 1_000_003]]) {
    if (gcd(num, den) !== 1n) continue;
    const D = BigInt(den), M = BigInt(num);
    for (let N = 2; N < Math.min(den, 800); N++) {
      const before = positions(num, den, N);
      let maxGap = 0n;
      for (let i = 0; i < N; i++) { const g = (i + 1 < N ? before[i + 1] : before[0] + D) - before[i]; if (g > maxGap) maxGap = g; }
      const np = (M * BigInt(N)) % D;          // the new point {N·a}
      // host arc: the consecutive pair straddling np
      let host = -1n;
      for (let i = 0; i < N; i++) {
        const a = before[i], b = (i + 1 < N ? before[i + 1] : before[0] + D);
        if (np >= a && np < b) { host = b - a; break; }
        if (i === N - 1) host = (before[0] + D) - before[N - 1]; // wrap arc
      }
      checks++;
      if (host === maxGap) landedInBiggest++;
      // new max after insertion
      const after = positions(num, den, N + 1);
      let maxAfter = 0n;
      for (let i = 0; i <= N; i++) { const g = (i + 1 <= N ? after[i + 1] : after[0] + D) - after[i]; if (g > maxAfter) maxAfter = g; }
      if (maxAfter <= maxGap) neverGrows++;
    }
  }
  console.log(`\n[4] dynamics of adding the next point {N·a}`);
  log(checks > 0 && landedInBiggest === checks, `the new point always lands inside a current LARGEST gap  (${landedInBiggest}/${checks})`);
  log(checks > 0 && neverGrows === checks, `the largest gap never grows — only ever splits  (${neverGrows}/${checks})`);
}

// ---------- TEST 5: sampled gap ratios for a golden proxy and a near-quarter turn ----------
// F41/F42 approximates 1/φ. Reflecting a turn preserves its gap lengths;
// the golden angle is 1 - 1/φ. This finite rational test does not prove the bound.
{
  const F = [0n, 1n]; while (F.length < 60) F.push(F[F.length - 1] + F[F.length - 2]);
  const num = F[41], den = F[42];          // a = F41/F42 = 1/φ to high precision
  const maxRatio = (num, den, Ns) => {
    let worst = 0;
    for (const N of Ns) { const lens = [...gapCounts(num, den, N).keys()].map(Number); worst = Math.max(worst, Math.max(...lens) / Math.min(...lens)); }
    return worst;
  };
  const Ns = []; for (let N = 5; N <= 5000; N += 7) Ns.push(N);
  const goldenRatio = maxRatio(num, den, Ns);
  const badRatio = maxRatio(2_500_001, 10_000_000, Ns); // ≈ 1/4 — clumps into spokes
  const PHI2 = ((1 + Math.sqrt(5)) / 2) ** 2;
  console.log(`\n[5] worst (largest gap / smallest gap) over ${Ns.length} sampled counts N=5,12,...,${Ns.at(-1)}`);
  console.log(`    golden proxy (a=F41/F42):  ${goldenRatio.toFixed(4)}`);
  console.log(`    round-ish angle (≈1/4):    ${badRatio.toExponential(3)}`);
  log(goldenRatio <= PHI2 + 1e-9, `F41/F42 gap ratio <= φ² + 1e-9 at all ${Ns.length} sampled counts (got ${goldenRatio.toFixed(4)})`);
  log(badRatio > 600_000, `the near-quarter turn has a sampled gap ratio above 600000 (got ${badRatio.toExponential(2)})`);
}

// ---------- TEST 6: exactly two lengths at 27 Fibonacci counts for F41/F42 ----------
{
  const F = [0n, 1n]; while (F.length < 60) F.push(F[F.length - 1] + F[F.length - 2]);
  const num = F[41], den = F[42];
  let ok = 0, tot = 0;
  for (let k = 4; k <= 30; k++) {           // F[k] from 3 up, kept below F[41]
    const N = Number(F[k]); if (N < 3 || BigInt(N) >= F[41]) continue;
    const sz = gapCounts(num, den, N).size; tot++; if (sz === 2) ok++;
  }
  console.log(`\n[6] F41/F42: number of distinct gap lengths at Fibonacci counts F4 through F30`);
  log(tot > 0 && ok === tot, `exactly two gap lengths at the 27 tested Fibonacci counts, N=3 through 832040  (${ok}/${tot})`);
}

console.log(`\n${PASS}/${PASS + FAIL} checks passed.`);
process.exit(FAIL ? 1 : 0);
