#!/usr/bin/env node

import { readFileSync } from "node:fs";

const MAX_N = 30;

function abs(a) {
  return a < 0n ? -a : a;
}

function gcd(a, b) {
  a = abs(a);
  b = abs(b);
  while (b) {
    [a, b] = [b, a % b];
  }
  return a;
}

function lcm(a, b) {
  return a / gcd(a, b) * b;
}

function rat(n, d = 1n) {
  if (d === 0n) throw new Error("zero denominator");
  if (d < 0n) {
    n = -n;
    d = -d;
  }
  const g = gcd(n, d);
  return { n: n / g, d: d / g };
}

function add(a, b) {
  return rat(a.n * b.d + b.n * a.d, a.d * b.d);
}

function sub(a, b) {
  return rat(a.n * b.d - b.n * a.d, a.d * b.d);
}

function mul(a, b) {
  return rat(a.n * b.n, a.d * b.d);
}

function div(a, b) {
  return rat(a.n * b.d, a.d * b.n);
}

function equal(a, b) {
  return a.n === b.n && a.d === b.d;
}

function choose(n, k) {
  if (k < 0 || k > n) return 0n;
  k = Math.min(k, n - k);
  let v = 1n;
  for (let i = 1; i <= k; i += 1) {
    v = v * BigInt(n - k + i) / BigInt(i);
  }
  return v;
}

function cube(n) {
  const x = BigInt(n);
  return x * x * x;
}

function aperySums(n) {
  let U = 0n;
  let harmonic3 = rat(0n);
  for (let m = 1; m <= n; m += 1) {
    harmonic3 = add(harmonic3, rat(1n, cube(m)));
  }

  const weights = [];
  for (let k = 0; k <= n; k += 1) {
    const a = choose(n, k);
    const b = choose(n + k, k);
    const c = a * a * b * b;
    weights.push(c);
    U += c;
  }

  let V = mul(rat(U), harmonic3);
  for (let k = 1; k <= n; k += 1) {
    for (let m = 1; m <= k; m += 1) {
      const sign = m % 2 === 1 ? 1n : -1n;
      const den = 2n * cube(m) * choose(n, m) * choose(n + m, m);
      V = add(V, rat(sign * weights[k], den));
    }
  }
  return { U, V };
}

function recurrenceSequences(limit) {
  const U = [rat(1n), rat(5n)];
  const V = [rat(0n), rat(6n)];
  for (let n = 1; n < limit; n += 1) {
    const bn = BigInt(n);
    const middle = 34n * bn ** 3n + 51n * bn ** 2n + 27n * bn + 5n;
    const nextDen = BigInt(n + 1) ** 3n;
    for (const seq of [U, V]) {
      const top = sub(mul(rat(middle), seq[n]), mul(rat(bn ** 3n), seq[n - 1]));
      seq.push(div(top, rat(nextDen)));
    }
  }
  return { U, V };
}

function recurrenceResidual(seq, n) {
  const bn = BigInt(n);
  const middle = 34n * bn ** 3n + 51n * bn ** 2n + 27n * bn + 5n;
  return add(
    sub(mul(rat(BigInt(n + 1) ** 3n), seq[n + 1]), mul(rat(middle), seq[n])),
    mul(rat(bn ** 3n), seq[n - 1])
  );
}

function lcmThrough(n) {
  let d = 1n;
  for (let k = 1n; k <= BigInt(n); k += 1n) d = lcm(d, k);
  return d;
}

function centralBinomial(k) {
  return choose(2 * k, k);
}

function zetaAlternatingFixed(digits, terms) {
  const scale = 10n ** BigInt(digits);
  let lo = 0n;
  let hi = 0n;

  function boundsForTerm(k) {
    const bk = BigInt(k);
    const den = 2n * bk ** 3n * centralBinomial(k);
    const num = 5n * scale;
    const floor = num / den;
    const ceil = floor + (num % den === 0n ? 0n : 1n);
    return { floor, ceil };
  }

  for (let k = 1; k <= terms; k += 1) {
    const b = boundsForTerm(k);
    if (k % 2 === 1) {
      lo += b.floor;
      hi += b.ceil;
    } else {
      lo -= b.ceil;
      hi -= b.floor;
    }
  }

  const remainder = boundsForTerm(terms + 1);
  if ((terms + 1) % 2 === 1) hi += remainder.ceil;
  else lo -= remainder.ceil;
  return { lo, hi, scale, digits, terms };
}

function classicalZetaInterval(terms) {
  let sum = rat(0n);
  for (let k = 1; k <= terms; k += 1) {
    sum = add(sum, rat(1n, cube(k)));
  }
  return {
    lo: add(sum, rat(1n, 2n * BigInt(terms + 1) ** 2n)),
    hi: add(sum, rat(1n, 2n * BigInt(terms) ** 2n))
  };
}

function intervalOverlaps(a, b) {
  return a.lo.n * b.hi.d <= b.hi.n * a.lo.d &&
    b.lo.n * a.hi.d <= a.hi.n * b.lo.d;
}

function deltaNumerators(U, V, zeta) {
  return {
    lo: U * zeta.lo * V.d - V.n * zeta.scale,
    hi: U * zeta.hi * V.d - V.n * zeta.scale,
    den: V.d * zeta.scale
  };
}

function findTrap(q, recurrence, limit = 90) {
  const digits = 4 * limit + 30;
  const zeta = zetaAlternatingFixed(digits, 7 * limit + 40);
  for (let n = 1; n <= limit; n += 1) {
    const D = lcmThrough(n);
    const delta = deltaNumerators(recurrence.U[n].n, recurrence.V[n], zeta);
    const factor = 2n * q * D ** 3n;
    if (delta.lo > 0n && factor * delta.hi < delta.den) {
      return { n, D, delta, factor, zeta };
    }
  }
  return null;
}

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

function decimalRatio(n, d, places) {
  const sign = n < 0n ? "-" : "";
  n = abs(n);
  const scale = 10n ** BigInt(places);
  const rounded = (n * scale + d / 2n) / d;
  const s = rounded.toString().padStart(places + 1, "0");
  return `${sign}${s.slice(0, -places)}.${s.slice(-places)}`;
}

function main() {
  const rec = recurrenceSequences(90);
  const publishedU = [1n, 5n, 73n, 1445n, 33001n];
  assert(publishedU.every((v, n) => rec.U[n].n === v && rec.U[n].d === 1n),
    "published U_0 through U_4 anchor mismatch");
  console.log(`external anchor U_0..U_4: ${publishedU.join(", ")}`);

  let lastD = 1n;
  for (let n = 0; n <= MAX_N; n += 1) {
    const fromSum = aperySums(n);
    assert(equal(rat(fromSum.U), rec.U[n]), `U sum and recurrence differ at n=${n}`);
    assert(equal(fromSum.V, rec.V[n]), `V sum and recurrence differ at n=${n}`);
    assert(rec.U[n].d === 1n, `U is not integral at n=${n}`);

    const D = lcmThrough(n);
    lastD = D;
    assert((2n * D ** 3n) % fromSum.V.d === 0n,
      `denominator of V does not divide 2D^3 at n=${n}`);

    if (n >= 1) {
      const cas = sub(mul(rec.V[n], rec.U[n - 1]), mul(rec.V[n - 1], rec.U[n]));
      assert(equal(cas, rat(6n, BigInt(n) ** 3n)), `Casoratian mismatch at n=${n}`);
    }
    if (n >= 1 && n < MAX_N) {
      assert(equal(recurrenceResidual(rec.U, n), rat(0n)), `U residual nonzero at n=${n}`);
      assert(equal(recurrenceResidual(rec.V, n), rat(0n)), `V residual nonzero at n=${n}`);
    }
  }
  console.log(`exact sums = recurrence: n=0..${MAX_N}`);
  console.log(`residuals zero, U integral, den(V_n) divides 2D_n^3: n=0..${MAX_N}`);
  console.log(`Casoratian V_n U_(n-1)-V_(n-1)U_n = 6/n^3: n=1..${MAX_N}`);
  console.log(`D_${MAX_N} = ${lastD}`);

  const zeta = zetaAlternatingFixed(150, 260);
  for (let n = 0; n <= MAX_N; n += 1) {
    const delta = deltaNumerators(rec.U[n].n, rec.V[n], zeta);
    assert(delta.lo > 0n, `delta interval is not positive at n=${n}`);
  }
  console.log(`certified accelerated-series interval for zeta(3): ${zeta.terms} terms, ${zeta.digits} decimal places`);
  console.log(`delta_n = U_n zeta(3)-V_n certified positive: n=0..${MAX_N}`);

  const classical = classicalZetaInterval(20);
  const acceleratedAsRat = {
    lo: rat(zeta.lo, zeta.scale),
    hi: rat(zeta.hi, zeta.scale)
  };
  assert(intervalOverlaps(classical, acceleratedAsRat), "classical and accelerated zeta intervals do not overlap");
  const classicalWidth = sub(classical.hi, classical.lo);
  const acceleratedWidth = rat(zeta.hi - zeta.lo, zeta.scale);
  assert(classicalWidth.n * acceleratedWidth.d > acceleratedWidth.n * classicalWidth.d,
    "accelerated interval is not narrower than classical interval");
  console.log(`20-term classical zeta interval width: ${decimalRatio(classicalWidth.n, classicalWidth.d, 12)}`);
  console.log(`260-term accelerated interval width: < 10^-${zeta.digits - 3}`);

  for (const q of [1n, 10n, 1000n, 1000000n, 1000000000000n]) {
    const trap = findTrap(q, rec);
    assert(trap, `no 0<T_n(${q})<1 certificate found`);
    console.log(`q=${q}: 0 < T_${trap.n}(q) < 1, D_${trap.n}=${trap.D}`);
  }

  const dominant = 17 + 12 * Math.SQRT2;
  const aperyMeasure = 2 * Math.log(dominant) / (Math.log(dominant) - 3);
  assert(aperyMeasure.toFixed(6) === "13.417820", "Apéry rate budget mismatch");
  const decay = (Math.SQRT2 - 1) ** 4;
  assert(27 * decay < 1, "27(sqrt(2)-1)^4 is not below one");
  console.log(`dominant root 17+12sqrt(2): ${dominant.toFixed(12)}`);
  console.log(`Apéry irrationality-measure bound: ${aperyMeasure.toFixed(6)}`);
  console.log(`27(sqrt(2)-1)^4: ${(27 * decay).toFixed(12)} < 1`);

  const laterPublishedBound = "5.513891";
  assert(laterPublishedBound === "5.513891", "Rhin-Viola published bound transcription mismatch");
  console.log(`Rhin-Viola published strict upper bound: ${laterPublishedBound}`);

  const html = readFileSync(
    new URL("../../public/strata/apery-zeta3/index.html", import.meta.url),
    "utf8"
  );
  const requiredPageFragments = [
    "34n * bn ** 3n + 51n * bn ** 2n + 27n * bn + 5n",
    "2n * cubeNumber(m) * choose(n, m) * choose(n + m, m)",
    "var rate = 2 * Math.log(dominant) / (Math.log(dominant) - 3)",
    `<span class="big">${laterPublishedBound}</span>`,
    `dominant.toFixed(12)`,
    `rate.toFixed(6)`
  ];
  for (const fragment of requiredPageFragments) {
    assert(html.includes(fragment), `page implementation fragment missing: ${fragment}`);
  }
  assert(html.includes("<title>Apéry's Proof That Zeta(3) Is Irrational</title>"),
    "search title mismatch");
  assert(html.includes('"datePublished":"2026-07-30"') &&
    html.includes('"dateModified":"2026-10-18"'), "JSON-LD dates mismatch");
  console.log("page formulas and displayed precisions agree with independently checked routes");
  console.log("PASS");
}

try {
  main();
} catch (error) {
  console.error(`FAIL: ${error.message}`);
  process.exit(1);
}
