#!/usr/bin/env node
// The entropy of printed English — offline verifier for the stratum
// "You Already Know the Rest" (the Verification Venue / quantitative-linguistics seam).
//
// WHAT THIS REPRODUCES, from a primary corpus committed under ./corpora/ and
// from Shannon's own published figures:
//
//   (0) The maximum. With a 27-symbol alphabet (A–Z + space) and no statistics
//       at all, every letter carries F0 = log2(27) = 4.755 bits. Shannon (1951)
//       rounds this to 4.76. This is the ceiling every later number falls below.
//
//   (1) The n-gram ladder, F1 ≥ F2 ≥ F3, computed directly on the corpus.
//       Shannon's defines FN = H(next symbol | preceding N−1 symbols):
//         F1 = H(X)                       (single-letter distribution)
//         F2 = H(X2|X1) = H(X1X2) − H(X1) (one letter of memory)
//         F3 = H(X3|X1X2)= H(X1X2X3)−H(X1X2)
//       Each rung uses *more* memory and predicts *better*, so entropy falls.
//       Shannon's reported 27-letter values: F1 4.03, F2 3.32, F3 3.1.
//       Corpus differences and finite-sample bias may affect these estimates;
//       this calculation does not separate them. F3 uses two preceding
//       letters of context. The verified anchors are F0 and the model-bound
//       inequalities below, not a population value inferred from this F3.
//
//   (2) Shannon's prediction bounds, eq. (17) of the 1951 paper. From the
//       guess-rank distribution q_i (the probability the correct next symbol is
//       a predictor's i-th guess, sorted q_1 ≥ q_2 ≥ … over the 27 ranks):
//
//         Σ_{i=1}^{27} i·(q_i − q_{i+1})·log2 i   ≤   F   ≤   − Σ q_i·log2 q_i
//         └────────── lower bound ──────────┘            └── upper bound ──┘
//
//       We verify the *machinery* two ways that need no human subject:
//        (2a) Algebraic sanity — degenerate q (always 1st guess) ⇒ both bounds
//             0; uniform q over 27 ⇒ both bounds = log2 27 (no predictability);
//             lower ≤ upper always; both ≤ F0.
//        (2b) The theorem ON REAL TEXT with an *ideal* predictor. For memory
//             order k = 0,1,2 we build the order-k Markov model of the corpus,
//             let the ideal predictor guess next symbols in order of model
//             probability, tally the empirical guess-rank distribution q, and
//             confirm  lower(q) ≤ F_{k+1} ≤ upper(q)  — Shannon's sandwich,
//             reproduced offline. As k grows the sandwich slides down, the
//             picture of his Fig. 4. The human game supplies illustrative
//             sample estimates, not guaranteed English-entropy bounds.
//
//   (3) The headline. Shannon's 100-letter prediction experiment put the
//       entropy of English between 0.6 and 1.3 bits/letter (his Fig. 4 / the
//       per-column table), a redundancy of "roughly 75%". Cover & King's 1978
//       convergent gambling estimate, ~1.3 bits/symbol, agrees. We print these
//       as cited historical estimates, not a guaranteed destination for the
//       live game or something this script recomputes (Shannon's Table I is not
//       reproduced here; that is stated, not hidden).
//
// SOURCES (verified against the primary texts):
//   Shannon, C.E. (1951) "Prediction and Entropy of Printed English",
//     Bell System Technical Journal 30:50–64. Eq. (17); §2 table
//     (F0 4.76, F1 4.03, F2 3.32, F3 3.1, F_word 2.14); §6 per-column bounds
//     (100 letters: upper 1.3, lower 0.6); Introduction ("redundancy of roughly 75%").
//   Cover, T.M. & King, R.C. (1978) "A Convergent Gambling Estimate of the
//     Entropy of English", IEEE Trans. Inf. Theory 24:413 (≈1.3 bits/symbol).
//   Corpus: Mary Shelley, *Frankenstein* (Project Gutenberg #84, public domain).
//
// Run:   node research/entropy-of-english/verify.mjs
// Emits: research/entropy-of-english/data.json   (what the page embeds)

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const CORP = path.join(HERE, 'corpora');

let pass = 0, fail = 0;
const log = (ok, msg) => { (ok ? pass++ : fail++); console.log(`${ok ? '  ✓' : '  ✗ FAIL'} ${msg}`); };
const log2 = (x) => Math.log(x) / Math.LN2;

// ───────────────────────── text → 27-symbol stream ─────────────────────────
// Alphabet: A–Z mapped to 0..25, space = 26. Everything else becomes a space,
// runs of space collapse to one. This is exactly Shannon's 27-symbol model.
function stripGutenberg(text) {
  let s = text;
  const a = s.search(/\*\*\* ?START OF (THE|THIS)/i);
  if (a >= 0) s = s.slice(s.indexOf('\n', a) + 1);
  const b = s.search(/\*\*\* ?END OF (THE|THIS)/i);
  if (b >= 0) s = s.slice(0, b);
  return s;
}
function normalize27(text) {
  const up = text.toUpperCase();
  const out = [];
  let lastSpace = true; // trim leading space
  for (let i = 0; i < up.length; i++) {
    const c = up.charCodeAt(i);
    if (c >= 65 && c <= 90) { out.push(c - 65); lastSpace = false; }
    else if (!lastSpace) { out.push(26); lastSpace = true; }
  }
  while (out.length && out[out.length - 1] === 26) out.pop();
  return out; // array of ints 0..26
}

// ───────────────────────── entropy primitives ─────────────────────────
function blockEntropy(stream, n) {
  // H of the distribution of length-n blocks, in bits.
  const counts = new Map();
  let total = 0;
  for (let i = 0; i + n <= stream.length; i++) {
    let key = 0;
    for (let j = 0; j < n; j++) key = key * 27 + stream[i + j];
    counts.set(key, (counts.get(key) || 0) + 1);
    total++;
  }
  let H = 0;
  for (const c of counts.values()) { const p = c / total; H -= p * log2(p); }
  return { H, total, distinct: counts.size };
}
function ngramLadder(stream) {
  const H1 = blockEntropy(stream, 1);
  const H2 = blockEntropy(stream, 2);
  const H3 = blockEntropy(stream, 3);
  return {
    F0: log2(27),
    F1: H1.H,                 // H(X)
    F2: H2.H - H1.H,          // H(X2|X1)
    F3: H3.H - H2.H,          // H(X3|X1X2)
    blocks: { H1: H1.H, H2: H2.H, H3: H3.H },
  };
}

// ───────────────────────── Shannon's bounds, eq. (17) ─────────────────────────
// q: array of rank probabilities (need not be pre-sorted/normalized; we do both).
// Ideal-model frequencies are nonincreasing. Sorting a human sample can change
// the lower expression; it does not establish bounds on English entropy.
function shannonBounds(qRaw) {
  let q = qRaw.slice().sort((a, b) => b - a);
  const Z = q.reduce((a, b) => a + b, 0) || 1;
  q = q.map(x => x / Z);
  // upper = −Σ q_i log2 q_i
  let upper = 0;
  for (const p of q) if (p > 0) upper -= p * log2(p);
  // lower = Σ_{i=1}^{N} i (q_i − q_{i+1}) log2 i      (q_{N+1} = 0)
  let lower = 0;
  for (let i = 1; i <= q.length; i++) {
    const qi = q[i - 1], qi1 = (i < q.length) ? q[i] : 0;
    lower += i * (qi - qi1) * log2(i);
  }
  return { lower, upper };
}

// ───────── ideal order-k predictor on real text → guess-rank distribution ─────────
// Build the order-k model, then for every position with full context, rank the
// 27 candidate next symbols by the model's conditional probability and record
// the rank at which the *actual* next symbol appears. Returns q (length 27),
// the true conditional entropy F_{k+1} of the model, and the 1st-guess rate.
function idealPredictor(stream, k) {
  // contextKey -> Int32Array(27) of counts
  const ctx = new Map();
  const ctxTotal = new Map();
  const keyOf = (i) => { let key = 0; for (let j = 0; j < k; j++) key = key * 27 + stream[i - k + j]; return key; };
  for (let i = k; i < stream.length; i++) {
    const key = keyOf(i);
    let row = ctx.get(key);
    if (!row) { row = new Float64Array(27); ctx.set(key, row); ctxTotal.set(key, 0); }
    row[stream[i]] += 1;
    ctxTotal.set(key, ctxTotal.get(key) + 1);
  }
  // true conditional entropy F_{k+1} = Σ_ctx p(ctx) H(next|ctx)
  let Fcond = 0, grand = 0;
  for (const t of ctxTotal.values()) grand += t;
  for (const [key, row] of ctx) {
    const tot = ctxTotal.get(key);
    let h = 0;
    for (let s = 0; s < 27; s++) { const c = row[s]; if (c > 0) { const p = c / tot; h -= p * log2(p); } }
    Fcond += (tot / grand) * h;
  }
  // guess-rank tally: rank actual symbol within its context's sorted candidates
  const rank = new Float64Array(28); // 1..27
  let n = 0;
  for (let i = k; i < stream.length; i++) {
    const key = keyOf(i);
    const row = ctx.get(key), tot = ctxTotal.get(key);
    const actual = stream[i];
    const pActual = row[actual] / tot;
    // rank = 1 + (number of symbols strictly more probable than actual),
    // ties broken so identical-probability symbols share the average rank band;
    // here we use a deterministic break by symbol index for a single integer rank.
    let higher = 0, tieBefore = 0;
    for (let s = 0; s < 27; s++) {
      const ps = row[s] / tot;
      if (ps > pActual) higher++;
      else if (ps === pActual && s < actual) tieBefore++;
    }
    const r = higher + tieBefore + 1;
    rank[r] += 1; n++;
  }
  const q = [];
  for (let r = 1; r <= 27; r++) q.push(rank[r] / n);
  const firstGuess = q[0];
  return { q, Fcond, firstGuess, contexts: ctx.size };
}

// ───────────────────────── run ─────────────────────────
console.log('\nThe entropy of printed English — verifier\n');

const raw = fs.readFileSync(path.join(CORP, 'frankenstein.txt'), 'utf8');
const full = normalize27(stripGutenberg(raw));
console.log(`  corpus: Frankenstein (Gutenberg #84) → ${full.length.toLocaleString()} symbols over the 27-letter alphabet\n`);

// (0) the ceiling
const F0 = log2(27);
log(Math.abs(F0 - 4.7549) < 1e-3, `F0 = log2(27) = ${F0.toFixed(4)} bits  (Shannon rounds to 4.76)`);

// (1) the ladder on the full corpus
const ladder = ngramLadder(full);
log(ladder.F1 < F0 && ladder.F1 > 3.8, `F1 = H(X)      = ${ladder.F1.toFixed(3)} bits  (Shannon 4.03; below the ceiling)`);
log(ladder.F2 < ladder.F1, `F2 = H(X2|X1)  = ${ladder.F2.toFixed(3)} bits  (Shannon 3.32; < F1 — one letter of memory helps)`);
log(ladder.F3 < ladder.F2, `F3 = H(X3|X1X2)= ${ladder.F3.toFixed(3)} bits  (Shannon 3.1; < F2; corpus and sampling effects not separated)`);

// (2a) bound machinery — algebraic sanity
{
  const degenerate = [1, ...Array(26).fill(0)];
  const uniform = Array(27).fill(1 / 27);
  const bd = shannonBounds(degenerate), bu = shannonBounds(uniform);
  log(Math.abs(bd.lower) < 1e-12 && Math.abs(bd.upper) < 1e-12,
    `bounds: always-first-guess ⇒ lower=${bd.lower.toFixed(3)}, upper=${bd.upper.toFixed(3)} (perfectly predictable → 0 bits)`);
  log(Math.abs(bu.lower - F0) < 1e-9 && Math.abs(bu.upper - F0) < 1e-9,
    `bounds: uniform 27 ⇒ lower=${bu.lower.toFixed(3)}, upper=${bu.upper.toFixed(3)} = log2 27 (no predictability → the ceiling)`);
}

// (2b) Shannon's sandwich on real text, ideal predictor, orders 0/1/2
const ideal = [];
for (const k of [0, 1, 2]) {
  const r = idealPredictor(full, k);
  const b = shannonBounds(r.q);
  const sandwich = b.lower - 1e-9 <= r.Fcond && r.Fcond <= b.upper + 1e-9;
  log(sandwich,
    `order-${k} ideal predictor: lower ${b.lower.toFixed(3)} ≤ F${k + 1} ${r.Fcond.toFixed(3)} ≤ upper ${b.upper.toFixed(3)} bits  (1st-guess ${(r.firstGuess * 100).toFixed(1)}%)`);
  ideal.push({ order: k, F: r.Fcond, lower: b.lower, upper: b.upper, firstGuess: r.firstGuess, q: r.q, contexts: r.contexts });
}
// the sandwich slides DOWN as memory grows (the shape of Shannon's Fig. 4)
log(ideal[0].upper > ideal[1].upper && ideal[1].upper > ideal[2].upper,
  `the sandwich descends with memory: upper ${ideal[0].upper.toFixed(2)} → ${ideal[1].upper.toFixed(2)} → ${ideal[2].upper.toFixed(2)} bits`);

// (3) the cited destination — Shannon's & Cover-King's numbers (not recomputed here)
const shannonPublished = {
  // §2 table, 27-letter alphabet
  ngram: { F0: 4.76, F1: 4.03, F2: 3.32, F3: 3.1, Fword: 2.14, F8approx: 2.3 },
  // §6 per-column experimental bounds for the entropy of 27-letter English (Fig. 4)
  // Ordinary columns N use N-1 known letters; the final test uses 100 known letters.
  columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 100],
  upper:  [4.03, 3.42, 3.0, 2.6, 2.7, 2.2, 2.8, 1.8, 1.9, 2.1, 2.2, 2.3, 2.1, 1.7, 2.1, 1.3],
  lower:  [3.19, 2.50, 2.1, 1.7, 1.7, 1.3, 1.8, 1.0, 1.0, 1.0, 1.3, 1.3, 1.2, 0.9, 1.2, 0.6],
  redundancyPct: 75, // Introduction: "redundancy of roughly 75%" at long range
  firstGuessExperiment: { letters: 129, correct: 89, pct: 69 },
};
const coverKing = { estimate: 1.3, note: 'convergent gambling estimate, IEEE TIT 1978 (≈1.34 average, ≈1.25–1.30 best subject)' };

// a short public-domain passage for the live game (opening of Frankenstein, Letter 1).
const GAME_PASSAGE_RAW =
  'You will rejoice to hear that no disaster has accompanied the commencement of an enterprise which you have regarded with such evil forebodings.';
const gamePassage = normalize27(GAME_PASSAGE_RAW); // ints 0..26
// a second, harder, more idiomatic one
const GAME_PASSAGE2_RAW =
  'I am already far north of London, and as I walk in the streets of Petersburgh, I feel a cold northern breeze play upon my cheeks.';
const gamePassage2 = normalize27(GAME_PASSAGE2_RAW);

// the corpus slice the live page recomputes its ladder on (must equal what we
// state the page shows). We embed a slice and report its ladder so live==offline.
const SLICE_LEN = 160000;
const slice = full.slice(0, SLICE_LEN);
const sliceLadder = ngramLadder(slice);
log(Math.abs(sliceLadder.F1 - ladder.F1) < 0.05,
  `embedded ${SLICE_LEN / 1000}k slice tracks the full book: F1 ${sliceLadder.F1.toFixed(3)} vs ${ladder.F1.toFixed(3)}`);

// ───────────────────────── emit ─────────────────────────
const symToChar = (s) => (s === 26 ? ' ' : String.fromCharCode(65 + s));
// A STABLE STAMP. This used to be `new Date().toISOString()`, unconditionally, so merely
// running the verifier rewrote data.json and left the working tree dirty, with an
// identical payload and a different date. coordination/publish.sh refuses to start on a
// dirty tree, so a read-only check was manufacturing work for whoever ran it next. The
// stamp now records when the CONTENT last changed, which is what a reader would take it
// to mean anyway: re-derive the payload, and keep the committed date if nothing moved.
// (This file is deterministic given the committed corpus, so "nothing moved" is the
// normal case.) Fixed 2026-08-15.
function stableStamp(file, payload) {
  const canon = (v) => {
    if (Array.isArray(v)) return '[' + v.map(canon).join(',') + ']';
    if (v && typeof v === 'object') return '{' + Object.keys(v).sort().map((k) => JSON.stringify(k) + ':' + canon(v[k])).join(',') + '}';
    return JSON.stringify(v);
  };
  try {
    const prev = JSON.parse(fs.readFileSync(file, 'utf8'));
    const a = { ...prev }, b = { ...payload };
    delete a.generated; delete b.generated;
    if (prev.generated && canon(a) === canon(b)) return prev.generated;
  } catch { /* no readable previous artifact: this run is when it was generated */ }
  return new Date().toISOString();
}

const out = {
  generated: null, // filled below, from stableStamp
  corpus: { name: 'Frankenstein (Mary Shelley, 1818)', gutenberg: 84, symbols: full.length },
  F0,
  ladderFull: ladder,
  sliceLadder,
  ideal,
  shannonPublished,
  coverKing,
  // the page embeds the cleaned slice as a plain string and recomputes the ladder live
  sliceText: slice.map(symToChar).join(''),
  game: [
    { text: gamePassage.map(symToChar).join(''), source: 'Frankenstein, Letter 1 (opening)' },
    { text: gamePassage2.map(symToChar).join(''), source: 'Frankenstein, Letter 1' },
  ],
};

console.log(`\n${pass}/${pass + fail} checks pass${fail ? ` — ${fail} FAILED` : ''}.\n`);
out.generated = stableStamp(path.join(HERE, 'data.json'), out);
fs.writeFileSync(path.join(HERE, 'data.json'), JSON.stringify(out));
const kb = (fs.statSync(path.join(HERE, 'data.json')).size / 1024).toFixed(0);
console.log(`wrote ${path.relative(process.cwd(), path.join(HERE, 'data.json'))} (${kb} KB)\n`);
process.exit(fail ? 1 : 0);
