#!/usr/bin/env node
// verify.mjs — Gabriel's Horn / Torricelli's acute hyperbolic solid.
//
// The solid of revolution of y = 1/x about the x-axis, for x in [1, b].
// Everything the stratum displays is recomputed here, offline, by methods
// independent of the ones on the page, and cross-checked. No claim ships that
// this file does not confirm.
//
//   Volume (to x=b):   V(b) = pi * INT_1^b (1/x)^2 dx = pi*(1 - 1/b)          -> pi
//   Lateral surface:   S(b) = 2*pi * INT_1^b (1/x) * sqrt(1 + 1/x^4) dx        -> infinity
//   Flat region area:  A(b) = INT_1^b (1/x) dx = ln b                          -> infinity
//   Volume/area ratio: t(b) = V(b) / S(b)                                      -> 0
//   Inside radial coat: C(h,b) = pi*INT_1^b [1/x^2 - max(1/x-h,0)^2] dx <= V(b)
//
// Run:  node research/gabriels-horn/verify.mjs
'use strict';
const PI = Math.PI;
let pass = 0, fail = 0;
const results = [];
function check(name, got, want, tol, unit = '') {
  const ok = Math.abs(got - want) <= tol;
  ok ? pass++ : fail++;
  results.push(`${ok ? 'PASS' : 'FAIL'}  ${name}: got ${fmt(got)}${unit}  want ${fmt(want)}${unit}  (tol ${tol})`);
  if (!ok) results.push(`      ^^^ MISMATCH  delta=${Math.abs(got - want)}`);
}
function fmt(x) {
  if (x === Infinity) return 'inf';
  if (Math.abs(x) !== 0 && (Math.abs(x) < 1e-3 || Math.abs(x) >= 1e6)) return x.toExponential(6);
  return (Math.round(x * 1e9) / 1e9).toString();
}

// ── independent integrators ──────────────────────────────────────────────
// composite Simpson (even N)
function simpson(f, a, b, N) {
  if (N % 2) N++;
  const h = (b - a) / N;
  let s = f(a) + f(b);
  for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * f(a + i * h);
  return (h / 3) * s;
}
// adaptive Simpson — a genuinely different control path, used to cross-check
function adaptiveSimpson(f, a, b, eps = 1e-12, depth = 50) {
  function aux(a, b, fa, fb, fm, S, depth) {
    const m = (a + b) / 2, lm = (a + m) / 2, rm = (m + b) / 2;
    const flm = f(lm), frm = f(rm);
    const Sl = (m - a) / 6 * (fa + 4 * flm + fm);
    const Sr = (b - m) / 6 * (fm + 4 * frm + fb);
    if (depth <= 0 || Math.abs(Sl + Sr - S) <= 15 * eps)
      return Sl + Sr + (Sl + Sr - S) / 15;
    return aux(a, m, fa, fm, flm, Sl, depth - 1) + aux(m, b, fm, fb, frm, Sr, depth - 1);
  }
  const m = (a + b) / 2, fa = f(a), fb = f(b), fm = f(m);
  const S = (b - a) / 6 * (fa + 4 * fm + fb);
  return aux(a, b, fa, fb, fm, S, depth);
}

// ── the geometry ─────────────────────────────────────────────────────────
const volClosed = b => PI * (1 - 1 / b);                 // exact antiderivative
const volIntegrand = x => (1 / (x * x));                 // (1/x)^2
const surfIntegrand = x => (1 / x) * Math.sqrt(1 + 1 / (x * x * x * x));
const areaClosed = b => Math.log(b);                     // flat 2-D region under 1/x

console.log('Gabriel\'s Horn — offline verification\n' + '='.repeat(56) + '\n');

// 1. Volume closed form vs numerical, at several b, and the limit = pi.
for (const b of [2, 10, 100, 1000, 1e6]) {
  const numV = PI * adaptiveSimpson(volIntegrand, 1, b, 1e-13);
  check(`V(${b}) closed vs numeric`, volClosed(b), numV, 1e-6);
}
check('V(b) -> pi as b->inf (closed form limit)', volClosed(1e12), PI, 1e-11);
// the volume is BOUNDED by pi for every finite b, and never reaches it
check('V(b) < pi strictly (b=10^9)', volClosed(1e9) < PI ? 0 : 1, 0, 0);

// 2. Surface: two independent integrators agree, and it exceeds 2*pi*ln b.
for (const b of [2, 10, 100, 1000]) {
  const sA = 2 * PI * adaptiveSimpson(surfIntegrand, 1, b, 1e-13);
  const sB = 2 * PI * simpson(surfIntegrand, 1, b, 2_000_000);
  check(`S(${b}) adaptive vs Simpson agree`, sA, sB, 1e-5);
  // strict lower bound: sqrt(1+1/x^4) > 1  =>  S(b) > 2*pi*ln b
  const lb = 2 * PI * Math.log(b);
  check(`S(${b}) > 2*pi*ln b`, sA > lb ? 0 : 1, 0, 0);
}

// 3. Surface DIVERGES logarithmically: S(b) - 2*pi*ln b -> a finite constant.
//    (integrand - 1/x ~ (1/2) x^-5 is integrable, so the excess converges.)
const excess = b => 2 * PI * adaptiveSimpson(surfIntegrand, 1, b, 1e-13) - 2 * PI * Math.log(b);
const C1 = excess(1e3), C2 = excess(1e5), C3 = excess(1e7);
check('S(b)-2*pi*ln b converges (1e3 vs 1e5)', C1, C2, 1e-4);
check('S(b)-2*pi*ln b converges (1e5 vs 1e7)', C2, C3, 1e-6);
console.log(`      [surface asymptote constant ~ ${fmt(C3)}; so S(b) ~ 2*pi*ln b + ${fmt(C3)} -> inf]`);
// and S itself is unbounded: grows past any ceiling
check('S(b) unbounded: S(1e8) > 100', 2 * PI * Math.log(1e8) < (2 * PI * adaptiveSimpson(surfIntegrand, 1, 1e8, 1e-11)) ? 0 : 1, 0, 0);
check('S(1e8) exceeds 110', 2 * PI * adaptiveSimpson(surfIntegrand, 1, 1e8, 1e-11) > 110 ? 0 : 1, 0, 0);

// 4. Volume-to-area ratio t(b) = V(b)/S(b) -> 0, not local fill thickness.
for (const b of [10, 1000, 1e6]) {
  const s = 2 * PI * adaptiveSimpson(surfIntegrand, 1, b, 1e-12);
  const t = volClosed(b) / s;
  results.push(`INFO  volume/area t(${b}) = V/S = ${fmt(t)}  (-> 0)`);
}
const tBig = volClosed(1e12) / (2 * PI * adaptiveSimpson(surfIntegrand, 1, 1e12, 1e-10));
check('volume/area t(1e12) < 0.02 (tending to 0)', tBig < 0.02 ? 0 : 1, 0, 0);

// 5. The flat 2-D region that is revolved is ITSELF infinite (area = ln b),
//    yet its solid of revolution is finite. The finiteness comes from the r^2.
for (const b of [10, 100]) check(`flat region area A(${b}) = ln b`, adaptiveSimpson(x => 1 / x, 1, b, 1e-13), areaClosed(b), 1e-8);
check('flat region area -> inf (A(1e9) > 20)', areaClosed(1e9) > 20 ? 0 : 1, 0, 0);

// 6. Inside paint is a subset of the fill. A requested inward radial depth h
//    is capped at the radius: discs with 1/x <= h fill completely. Integrate
//    annular areas in log coordinates, independently of the page's closed form.
const coatNumeric = (h, b) => PI * adaptiveSimpson(u => {
  const r = Math.exp(-u), depth = Math.min(h, r);
  return (2*r*depth - depth*depth) / r;
}, 0, Math.log(b), 1e-12);
for (const h of [0.1, 0.001]) {
  results.push(`INFO  inside radial coat h=${h}, b=1e6: ${fmt(coatNumeric(h, 1e6))} vol; bounded by fill ${fmt(volClosed(1e6))}`);
}

// 7. Page display cross-check: the exact numbers the reader will read.
check('display V(2) = pi/2', volClosed(2), PI / 2, 1e-12);
check('display S(2)', 2 * PI * adaptiveSimpson(surfIntegrand, 1, 2, 1e-13), 5.0164198, 1e-4);
check('display S(10)', 2 * PI * adaptiveSimpson(surfIntegrand, 1, 10, 1e-13), 15.177450, 1e-4);
check('display S(100)', 2 * PI * adaptiveSimpson(surfIntegrand, 1, 100, 1e-13), 29.645097, 1e-4);
check('display S(1000)', 2 * PI * adaptiveSimpson(surfIntegrand, 1, 1000, 1e-13), 44.112666, 1e-4);

// ── report ─────────────────────────────────────────────────────────────
console.log(results.join('\n'));
console.log('\n' + '='.repeat(56));
console.log(`${pass}/${pass + fail} checks passed${fail ? '  — ' + fail + ' FAILED' : ''}`);
process.exit(fail ? 1 : 0);
