#!/usr/bin/env node
// research/why-anything-to-the-zero-is-one/verify.mjs
// Recompute — in front of you — every numeric claim the stratum
// "Why Does Anything to the Zero Power Equal One?" makes.
//
// The page has two halves, and this verifier mirrors them:
//   A. x^0 = 1 is FORCED, three independent ways that all agree
//      (descending-powers ladder · the exponent law · the empty product).
//   B. 0^0 is the honest exception: its VALUE is 1 by convention, but its
//      LIMIT is indeterminate — the two-variable function x^y has no limit at
//      the origin, and can be steered to ANY value in [0,1] by choice of path.
//
//   node research/why-anything-to-the-zero-is-one/verify.mjs
//
// Pure Node, no deps. Exit code is nonzero if any check fails.

let fails = 0;
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));
const ok = (name, cond, extra = "") => {
  if (!cond) fails++;
  console.log(`${cond ? "  ok" : "FAIL"}  ${name}${extra ? "   " + extra : ""}`);
};
const sec = (t) => console.log("\n" + t);

// ----------------------------------------------------------------------------
sec("A1. The descending-powers ladder — each step down divides by the base, landing on 1");
// b^3, b^2, b^1, b^0 should be b^3, then /b each step; b^0 must be 1 for b != 0.
for (const b of [2, 10, 3, 0.5, -2, 7]) {
  const ladder = [3, 2, 1, 0].map((k) => Math.pow(b, k));
  // every step down is exactly a division by b
  let stepsOk = true;
  for (let i = 0; i < 3; i++) if (!approx(ladder[i] / b, ladder[i + 1])) stepsOk = false;
  ok(`base ${b}: ${ladder.map((x)=>+x.toFixed(4)).join(" → ")}  (each ÷${b}), lands on 1`,
     stepsOk && approx(ladder[3], 1), `b^0=${ladder[3]}`);
}

sec("A1b. At b = 0 the ladder BREAKS — the last step would be 0 ÷ 0, which is undefined");
{
  const ladder = [3, 2, 1].map((k) => Math.pow(0, k)); // 0,0,0
  const wouldDivide = ladder[2] / 0; // 0/0 -> NaN
  ok("0^3,0^2,0^1 are all 0, and 0^1 ÷ 0 = 0/0 is NaN (no value forced)",
     ladder.every((x) => x === 0) && Number.isNaN(wouldDivide), `0/0 = ${wouldDivide}`);
}

// ----------------------------------------------------------------------------
sec("A2. The exponent law forces it: b^a = b^(a+0) = b^a · b^0  ⇒  b^0 = 1  (b ≠ 0)");
for (const b of [2, 10, 3, 0.5, 7]) {
  for (const a of [1, 2, 5]) {
    const lhs = Math.pow(b, a);
    const rhs = Math.pow(b, a) * Math.pow(b, 0); // b^a · b^0
    ok(`b=${b}, a=${a}: b^a (${lhs}) = b^a·b^0 (${rhs}) only if b^0=1`,
       approx(lhs, rhs) && approx(Math.pow(b, 0), 1));
  }
}

// ----------------------------------------------------------------------------
sec("A3. The empty product: b^n is 'multiply n copies of b'; b^0 multiplies ZERO copies = the identity 1");
// Build b^n by folding a multiply over an array of n copies; the empty fold is the seed 1.
function powByFold(b, n) { let acc = 1; for (let i = 0; i < n; i++) acc *= b; return acc; }
for (const b of [2, 10, 3, 7]) {
  ok(`empty product for base ${b}: fold over 0 copies = 1 (= Math.pow(${b},0))`,
     powByFold(b, 0) === 1 && approx(powByFold(b, 0), Math.pow(b, 0)));
}
// the same reason 0! = 1 (empty product of the integers 1..0)
{
  const fact = (n) => { let a = 1; for (let i = 2; i <= n; i++) a *= i; return a; };
  ok("sibling: 0! = 1 is the same empty product (0! = product of no factors)", fact(0) === 1);
}

// ----------------------------------------------------------------------------
sec("A4. Set-theoretic value: 0^0 = |{functions ∅ → ∅}| = 1 (the empty function)");
// m^n counts functions from an n-set to an m-set. Enumerate for small m,n; 0^0 must be 1.
function countFunctions(n, m) {
  // number of functions from an n-element set into an m-element set = m^n
  // enumerate assignments to be concrete (n,m small)
  if (n === 0) return 1; // exactly one function out of the empty set (the empty function)
  let total = 0;
  const assign = new Array(n).fill(0);
  function rec(i) {
    if (i === n) { total++; return; }
    for (let v = 0; v < m; v++) { assign[i] = v; rec(i + 1); }
  }
  rec(0);
  return total;
}
ok("functions ∅→∅ : exactly 1 (so 0^0 = 1 as a cardinality)", countFunctions(0, 0) === 1);
ok("cross-check m^n counting: functions {a,b}→{x,y,z} = 3^2 = 9", countFunctions(2, 3) === 9, `got ${countFunctions(2,3)}`);
ok("cross-check: functions {a,b,c}→∅ = 0^3 = 0 (impossible)", countFunctions(3, 0) === 0);

// ----------------------------------------------------------------------------
sec("A5. Analysis NEEDS 0^0 = 1: the power series e^x = Σ x^n/n! only gives e^0 = 1 with the n=0 term = 0^0/0! = 1");
{
  function expSeries(x, terms, zeroPow) {
    // term n = x^n / n!  — but write the n=0 term as (0^0 or whatever) explicitly at x=0
    let sum = 0, fact = 1;
    for (let n = 0; n < terms; n++) {
      if (n > 0) fact *= n;
      const xn = (n === 0 && x === 0) ? zeroPow : Math.pow(x, n);
      sum += xn / fact;
    }
    return sum;
  }
  ok("e^0 via the series with 0^0 := 1 gives 1", approx(expSeries(0, 20, 1), 1), `= ${expSeries(0,20,1)}`);
  ok("e^0 via the series with 0^0 := 0 gives the WRONG answer 0", approx(expSeries(0, 20, 0), 0), `= ${expSeries(0,20,0)}`);
  ok("(continuity check) the series at x=1 reproduces e", approx(expSeries(1, 30, 1), Math.E, 1e-9));
}

// ----------------------------------------------------------------------------
sec("B1. But as a LIMIT, x^y has NO limit at the origin — three standard paths give three answers");
// Along y=0 (x→0):  x^0 = 1
{
  let v; for (const x of [1e-2, 1e-4, 1e-8]) v = Math.pow(x, 0);
  ok("path 1 — hug the x-axis (y=0): x^0 → 1", approx(v, 1), `→ ${v}`);
}
// Along x=0 (y→0+):  0^y = 0
{
  let v; for (const y of [1e-2, 1e-4, 1e-8]) v = Math.pow(0, y);
  ok("path 2 — hug the y-axis (x=0): 0^y → 0", v === 0, `→ ${v}`);
}
// Along y=x (x→0+):  x^x → 1, because x·ln x → 0
{
  const xs = [1e-1, 1e-2, 1e-4, 1e-6, 1e-9];
  const vals = xs.map((x) => Math.pow(x, x));
  const shrinking = xs.map((x) => x * Math.log(x));
  ok("path 3 — the diagonal (y=x): x^x → 1 (since x·ln x → 0)",
     approx(vals[vals.length - 1], 1, 1e-6) && approx(shrinking[shrinking.length - 1], 0, 1e-6),
     `x^x: ${vals.map((v)=>+v.toFixed(6)).join(", ")}`);
  // x·ln x is monotonically → 0 from below over this range
  ok("   evidence: x·ln x → 0", shrinking.every((s, i) => i === 0 || Math.abs(s) < Math.abs(shrinking[i - 1])),
     `x·ln x: ${shrinking.map((s)=>s.toExponential(2)).join(", ")}`);
}

// ----------------------------------------------------------------------------
sec("B2. The killer demo: you can STEER the limit to ANY target L in (0,1)");
// Path: x = e^{-1/t}, y = c·t, t→0+.  Then y·ln x = (c·t)(−1/t) = −c EXACTLY, so x^y = e^{−c},
// constant along the whole path. Choose c = −ln L to hit any target L in (0,1).
{
  for (const L of [0.5, 0.25, 0.1, 0.9, 1 / Math.E]) {
    const c = -Math.log(L); // so e^{-c} = L
    // walk the path inward; compute x^y two ways: direct pow (may underflow) and via the exact exponent
    const results = [];
    for (const t of [0.2, 0.1, 0.05]) {
      const x = Math.exp(-1 / t);
      const y = c * t;
      const exact = Math.exp(y * Math.log(x)); // = e^{-c} for every t, no underflow
      results.push(exact);
    }
    const constant = results.every((r) => approx(r, L, 1e-9));
    ok(`steer to L=${(+L.toFixed(4))}: pick c=${c.toFixed(4)}, then x^y = e^(−c) = ${results[0].toFixed(6)} at every t`,
       constant, `values along path: ${results.map((r)=>r.toFixed(6)).join(", ")}`);
  }
  ok("   the exponent y·ln x is exactly −c and CONSTANT along the path (that's why the limit is pinned to e^(−c))",
     approx((3 * 0.05) * Math.log(Math.exp(-1 / 0.05)), -3) && approx((3 * 0.1) * Math.log(Math.exp(-1 / 0.1)), -3),
     "checked c=3 at two t");
}

// ----------------------------------------------------------------------------
sec("B3. The endpoints 0 and 1 are reachable too — so the full set of limit values is the closed interval [0,1]");
{
  // → 1 along the x-axis, → 0 along the y-axis (already shown in B1); confirm 0 as a genuine limit target:
  let v; for (const t of [0.1, 0.01, 0.001]) v = Math.pow(0, t); // exactly 0
  ok("target 0 reachable (x=0, y→0+): 0^y ≡ 0", v === 0);
  // → 1 reachable and is also the algebraic value; interval endpoints both attained ⇒ [0,1] is the limit set
  ok("target 1 reachable (y=0, x→0+): x^0 ≡ 1", Math.pow(1e-9, 0) === 1);
}

// ----------------------------------------------------------------------------
sec("SUMMARY");
console.log(`\n${fails === 0 ? "ALL CHECKS PASSED" : fails + " CHECK(S) FAILED"}`);
process.exit(fails === 0 ? 0 : 1);
