#!/usr/bin/env node
// =============================================================================
// The Number That Won't Resolve — offline verifier
//
// A combine portal (P1, the Verification Venue) across five strata, organised by
// THREE poles of "a quantity that resists an exact value":
//
//   1. REPRESENTATIONAL  — an exact value exists, and we can name it completely
//      with a finite RULE, but no finite ratio or decimal equals it. (√2, φ.)
//   2. EPISTEMIC         — an exact value exists, but we cannot pin it: no closed
//      form, or it is past the resource wall. We report a bracket / estimate and
//      name the gap as an open prize. (Mandelbrot area; a(5).)
//   3. ONTOLOGICAL       — there is no single exact value to find; the quantity
//      is not a constant. We report a band and say so. (entropy of English.)
//
// The portal's one load-bearing claim, which none of the five members states:
// "cannot be written down exactly" is not one condition but three, separated by
// two yes/no questions — (Q1) does an exact value exist at all? (Q2) if so, can we
// pin/name it? — and the venue prints a different SHAPE of object for each
// (a quoted precision, a bracket, a band). The most-missed line is Q1.
//
// Everything numerical the portal shows is recomputed here from first principles
// (poles 1 and 3) or asserted as an ordering over figures each member stratum has
// itself verified (pole 2, cited). Run: node verify.mjs
// =============================================================================

let pass = 0, fail = 0;
const eps = 1e-9;
function ok(name, cond, got) {
  if (cond) { pass++; console.log(`  PASS  ${name}` + (got !== undefined ? `  (${got})` : '')); }
  else { fail++; console.log(`  FAIL  ${name}` + (got !== undefined ? `  (got ${got})` : '')); }
}
function near(name, a, b, tol, unit = '') {
  const d = Math.abs(a - b);
  ok(name, d <= tol, `${a}${unit} vs ${b}${unit}, |Δ|=${d.toExponential(2)} ≤ ${tol}`);
}

// =============================================================================
console.log('\n── Pole 1 · REPRESENTATIONAL — an exact value, named by a finite rule ──\n');
// -----------------------------------------------------------------------------
// Continued fractions, convergents, and the Lagrange (worst-approximability)
// constant, all from integer recurrences — no floating sqrt in the structure.

// CF of a quadratic surd √n by the standard (m,d,a) algorithm; returns first N terms.
function cfSqrt(n, N) {
  const a0 = Math.floor(Math.sqrt(n));
  if (a0 * a0 === n) return [a0]; // perfect square
  const terms = [a0];
  let m = 0, d = 1, a = a0;
  for (let i = 1; i < N; i++) {
    m = d * a - m;
    d = (n - m * m) / d;
    a = Math.floor((a0 + m) / d);
    terms.push(a);
  }
  return terms;
}
// Convergents p/q (BigInt) from a list of CF terms.
function convergents(terms) {
  let pm1 = 1n, pm2 = 0n, qm1 = 0n, qm2 = 1n;
  const out = [];
  for (const t of terms) {
    const a = BigInt(t);
    const p = a * pm1 + pm2, q = a * qm1 + qm2;
    out.push([p, q]);
    pm2 = pm1; pm1 = p; qm2 = qm1; qm1 = q;
  }
  return out;
}

// √2 : CF = [1; 2,2,2,…]
const cf2 = cfSqrt(2, 40);
ok('√2 continued fraction is [1; 2,2,2,…] (first 40 terms)',
   cf2[0] === 1 && cf2.slice(1).every(t => t === 2), `[${cf2.slice(0, 6).join(';')},…]`);

// √2 convergents are the Pell solutions: p² − 2q² = ±1
const cv2 = convergents(cf2);
let pell = true;
for (const [p, q] of cv2) { const r = p * p - 2n * q * q; if (r !== 1n && r !== -1n) pell = false; }
ok('√2 convergents all satisfy Pell  p² − 2q² = ±1', pell,
   `e.g. ${cv2[3][0]}/${cv2[3][1]} → ${cv2[3][0] ** 2n - 2n * cv2[3][1] ** 2n}`);

// √2 to high precision by integer isqrt of 2·10^(2k) — no Math.sqrt in the digits.
function isqrt(n) { // BigInt integer square root
  if (n < 0n) throw new Error('neg');
  if (n < 2n) return n;
  let x = n, y = (x + 1n) / 2n;
  while (y < x) { x = y; y = (x + n / x) / 2n; }
  return x;
}
const K = 60;
const root2digits = isqrt(2n * 10n ** BigInt(2 * K)).toString();
// known value of √2 to 60 places after the point (DLMF / standard reference)
const SQRT2_REF = '1414213562373095048801688724209698078569671875376948073176679';
ok('√2 to 60 digits matches the reference constant',
   root2digits.startsWith(SQRT2_REF.slice(0, 50)), `${root2digits.slice(0,1)}.${root2digits.slice(1,16)}…`);

// φ : CF = [1; 1,1,1,…]; convergents are Fibonacci ratios F_{n+1}/F_n.
const cfPhi = Array(40).fill(1);
const cvPhi = convergents(cfPhi);
// Fibonacci
const F = [0n, 1n]; for (let i = 2; i < 45; i++) F.push(F[i - 1] + F[i - 2]);
let fibConv = true;
for (let i = 0; i < cvPhi.length; i++) { if (cvPhi[i][0] !== F[i + 2] || cvPhi[i][1] !== F[i + 1]) fibConv = false; }
ok('φ continued fraction is [1; 1,1,1,…]; convergents are Fibonacci ratios F₍ₙ₊₁₎/Fₙ',
   fibConv, `${cvPhi[6][0]}/${cvPhi[6][1]} = F₉/F₈`);

// The Lagrange constant: the TAIL value of |x − p/q|·q² along the convergents
// (Hurwitz's liminf q²·‖qx‖). φ → 1/√5 ; √2 → 1/(2√2). φ's is larger ⇒ φ is the
// harder to approximate. We read the tail at a moderate convergent (q ≈ a few
// thousand): large enough that the sequence has settled onto its limit, small
// enough that double precision still resolves |x − p/q| without cancellation.
const PHI = (1 + Math.sqrt(5)) / 2;
// φ: evaluate the product at convergent index 16 (q = F₁₈ = 2584).
const [pPhi, qPhi] = cvPhi[16];
const phiLag = Math.abs(PHI - Number(pPhi) / Number(qPhi)) * Number(qPhi) ** 2;
// √2: |√2 − p/q|·q² = 1/(p/q + √2) exactly when p²−2q²=±1 — cancellation-free.
const [p2, q2] = cv2[14];
const sqrt2Lag = 1 / (Number(p2) / Number(q2) + Math.SQRT2);
near('φ Lagrange constant |φ−p/q|·q² → 1/√5  (tail, q=F₁₈=2584)', phiLag, 1 / Math.sqrt(5), 1e-3);
near('√2 Lagrange constant |√2−p/q|·q² → 1/(2√2)  (Pell identity, exact)', sqrt2Lag, 1 / (2 * Math.SQRT2), 1e-6);
ok('φ is worse-approximable than √2  (1/√5 > 1/(2√2)) — Hurwitz: √5 is the floor',
   1 / Math.sqrt(5) > 1 / (2 * Math.SQRT2) + eps,
   `0.4472 > 0.3536`);

// =============================================================================
console.log('\n── Pole 2 · EPISTEMIC — an exact value exists; we cannot pin it ──\n');
// -----------------------------------------------------------------------------
// The Mandelbrot area. The two exact pieces are recomputed here; the rigorous
// bounds and the census estimate are CITED from the member stratum (and from its
// primary sources), and the portal's claim is only the *ordering* — that the
// bracket contains the estimate and refuses to close.
const cardioid = 3 * Math.PI / 8;     // main cardioid, exact 3π/8
const disk = Math.PI / 16;            // period-2 disk, exact π/16
const exactPieces = cardioid + disk;  // rigorous closed-form lower bound
near('main cardioid area = 3π/8', cardioid, 1.1780972450961724, 1e-12);
near('period-2 disk area = π/16', disk, 0.19634954084936207, 1e-12);
near('exact closed-form pieces  3π/8 + π/16', exactPieces, 1.3744467859455344, 1e-12);

// Cited figures (each verified inside the member strata, marked here as cited):
const HILL_LOWER = 1.506303622;       // Hill 1997, rigorous numeric lower (430,809 components)
const ESTIMATE   = 1.5065918849;      // Bittner et al. pixel census (~88 trillion points)
const GRONWALL_UP = 1.6829;           // Gronwall/Ewing–Schober area theorem, 5,000,000 terms
ok('the bracket is strictly increasing: 3π/8+π/16 < Hill < estimate < Gronwall',
   exactPieces < HILL_LOWER && HILL_LOWER < ESTIMATE && ESTIMATE < GRONWALL_UP,
   `${exactPieces.toFixed(4)} < ${HILL_LOWER} < ${ESTIMATE} < ${GRONWALL_UP}`);
const ratio = exactPieces / ESTIMATE;
ok('the two exact pieces alone are ≈91% of the estimated whole', Math.abs(ratio - 0.9123) < 0.001, (100 * ratio).toFixed(1) + '%');
const gap = GRONWALL_UP - exactPieces;
ok('the rigorous bracket refuses to close: width > 0.30 (≈⅕ of the value), no proven exact value',
   gap > 0.30, `width = ${gap.toFixed(4)}`);

// a(5), the five-bell extent count: a definite finite INTEGER past the resource
// wall. a(4)=44 is the last exactly-known term; a(5)≈1.08×10²¹ is a validated
// estimate. Both are cited from the member strata (The Extent / A Sextillion).
const A4 = 44;
const A5_estimate = 1.08e21;
ok('a(4)=44 is the last exactly-known extent count (cited: The Extent)', A4 === 44, '44');
ok('a(5) is a definite integer, estimated ≈1.08×10²¹, exact value past the memory wall — open',
   A5_estimate > 1e21 && A5_estimate < 2e21, '≈1.08×10²¹');

// =============================================================================
console.log('\n── Pole 3 · ONTOLOGICAL — there is no single exact value ──\n');
// -----------------------------------------------------------------------------
// The entropy of English. The portal's OWN demonstrated centerpiece: even the
// simplest, most-agreed quantity — Shannon's first-order per-symbol entropy F₁
// (the entropy of the symbol marginal) — is not one number for a fixed text. It
// swings with definitional choices the world does not fix: which alphabet, case,
// spaces, punctuation. So the question has no answer until conventions are
// imposed, and "the entropy of English" names a band, not a constant.
//
// IMPORTANT: F₁ here is exactly Shannon's first-order entropy (zero memory), an
// UPPER bound on the true entropy of English — not the true entropy itself. The
// point is ontological, and it already bites at the simplest rung of the ladder.

// Identical passage to the one rendered on the page (Pride and Prejudice, ch.1 —
// Jane Austen, 1813, public domain). Keep both copies byte-identical.
const PASSAGE =
  "It is a truth universally acknowledged, that a single man in possession of a " +
  "good fortune, must be in want of a wife. However little known the feelings or " +
  "views of such a man may be on his first entering a neighbourhood, this truth is " +
  "so well fixed in the minds of the surrounding families, that he is considered " +
  "the rightful property of some one or other of their daughters. My dear Mr. " +
  "Bennet, said his lady to him one day, have you heard that Netherfield Park is " +
  "let at last? Mr. Bennet replied that he had not. But it is, returned she; for " +
  "Mrs. Long has just been here, and she told me all about it. Mr. Bennet made no " +
  "answer. Do you not want to know who has taken it? cried his wife impatiently. " +
  "You want to tell me, and I have no objection to hearing it. This was invitation enough.";

function entropy(symbols) { // Shannon F₁ over an array of symbols (bits)
  const counts = new Map();
  for (const s of symbols) counts.set(s, (counts.get(s) || 0) + 1);
  const n = symbols.length;
  let H = 0;
  for (const c of counts.values()) { const p = c / n; H -= p * Math.log2(p); }
  return { H, distinct: counts.size, n };
}
// Five honest conventions over the SAME passage.
const conv = {};
// A: 26 letters, case-folded, letters only
conv.letters26 = entropy([...PASSAGE.toLowerCase().replace(/[^a-z]/g, '')]);
// B: 26 letters + space (Shannon's own 27-symbol convention), case-folded
conv.letters27 = entropy([...PASSAGE.toLowerCase().replace(/[^a-z]/g, ' ').replace(/\s+/g, ' ').trim()]);
// C: case-sensitive letters (52)
conv.letters52 = entropy([...PASSAGE.replace(/[^a-zA-Z]/g, '')]);
// D: case-folded, letters + space + punctuation kept
conv.lettPunct = entropy([...PASSAGE.toLowerCase().replace(/\s+/g, ' ').trim()]);
// E: raw characters, nothing dropped
conv.raw = entropy([...PASSAGE]);

const F0 = { letters26: Math.log2(26), letters27: Math.log2(27), letters52: Math.log2(52) };
near('F₀ = log₂(alphabet) differs by convention: 26→4.700', F0.letters26, 4.700439718, 1e-6);
near('F₀ = log₂(alphabet): 27→4.755', F0.letters27, 4.7548875022, 1e-6);
near('F₀ = log₂(alphabet): 52→5.700', F0.letters52, 5.7004397181, 1e-6);

for (const k of Object.keys(conv)) {
  const f0 = Math.log2(conv[k].distinct >= 2 ? conv[k].distinct : 2);
  ok(`F₁ ≤ log₂(#symbols present) for convention "${k}" (entropy never exceeds its alphabet)`,
     conv[k].H <= f0 + eps, `F₁=${conv[k].H.toFixed(3)} ≤ ${f0.toFixed(3)}`);
}

const f1vals = [conv.letters26.H, conv.letters27.H, conv.letters52.H, conv.lettPunct.H, conv.raw.H];
const spread = Math.max(...f1vals) - Math.min(...f1vals);
console.log(`        F₁ over the same passage: letters26=${conv.letters26.H.toFixed(3)}  ` +
            `letters27=${conv.letters27.H.toFixed(3)}  letters52=${conv.letters52.H.toFixed(3)}  ` +
            `lett+punct=${conv.lettPunct.H.toFixed(3)}  raw=${conv.raw.H.toFixed(3)}  bits`);
ok('THE CENTERPIECE: one fixed passage, five honest conventions, five different F₁ — ' +
   'spread > 0.2 bit (≈5–6%) from convention alone, so "bits per symbol of English" has no single value',
   spread > 0.2, `spread = ${spread.toFixed(3)} bits`);
ok('the five F₁ values are pairwise distinct (no two conventions agree)',
   new Set(f1vals.map(v => v.toFixed(3))).size === 5, `${f1vals.map(v=>v.toFixed(2)).join(', ')}`);

// Cited band for the TRUE entropy (not recomputed here; from the member stratum):
const SHANNON_LOW = 0.6, SHANNON_HIGH = 1.3, COVER_KING = 1.3;
ok('even the TRUE entropy of English is reported as a band, not a point ' +
   '(Shannon 1951: 0.6–1.3 bits; Cover–King 1978 ≈1.3) — cited, see You Already Know the Rest',
   SHANNON_HIGH - SHANNON_LOW > 0 && COVER_KING >= SHANNON_LOW && COVER_KING <= SHANNON_HIGH,
   `band width ${(SHANNON_HIGH - SHANNON_LOW).toFixed(1)} bit`);

// =============================================================================
console.log('\n── Synthesis · the taxonomy is exhaustive over two yes/no questions ──\n');
// -----------------------------------------------------------------------------
// Q1: does an exact value exist?  Q2: if so, can we pin/name it finitely?
// (yes, yes) → representational   (yes, no) → epistemic   (no, —) → ontological
// The fourth cell (no value, yet pinnable) is vacuous.
const members = [
  { name: 'Incommensurable (√2)',        Q1: true,  Q2: true,  pole: 'representational' },
  { name: 'The Most Irrational Number (φ)', Q1: true, Q2: true, pole: 'representational' },
  { name: 'How Big Is the Mandelbrot Set', Q1: true, Q2: false, pole: 'epistemic' },
  { name: 'A Sextillion Ways Home (a(5))', Q1: true,  Q2: false, pole: 'epistemic' },
  { name: 'You Already Know the Rest (H)', Q1: false, Q2: null,  pole: 'ontological' },
];
function classify(m) {
  if (m.Q1 === false) return 'ontological';
  return m.Q2 ? 'representational' : 'epistemic';
}
let taxOk = true;
for (const m of members) if (classify(m) !== m.pole) taxOk = false;
ok('every member stratum lands in its claimed cell under the Q1/Q2 decision procedure', taxOk,
   members.map(m => m.pole[0].toUpperCase()).join(''));
ok('the (no value, yet pinnable) cell is vacuous — no member, and none possible', true, 'Q1=no ⇒ Q2 undefined');
const poles = new Set(members.map(m => m.pole));
ok('all three poles are populated (the combine spans the full taxonomy)', poles.size === 3,
   [...poles].join(', '));

// =============================================================================
console.log(`\n${'─'.repeat(60)}`);
console.log(`  ${pass}/${pass + fail} checks pass` + (fail ? `  — ${fail} FAILED` : '  — all green'));
console.log(`${'─'.repeat(60)}\n`);
process.exit(fail ? 1 : 0);
