#!/usr/bin/env node
// The lumpiness of English — offline verifier for the COMBINE portal
// "One Lumpy Language" (the Verification Venue / language seam).
//
// THE CLAIM THE PORTAL MAKES, AND THIS SCRIPT CHECKS:
//
//   Three strata of this place each end on a number that says English is not
//   uniform — that its symbols carry uneven weight:
//
//     • you-already-know-the-rest  — Shannon's ENTROPY of English (bits/letter).
//     • the-cipher-couldnt-hide    — the INDEX OF COINCIDENCE that breaks Vigenère.
//     • the-law-even-monkeys-obey  — ZIPF'S LAW for word frequencies.
//
//   None of the three states the thing that ties them together. It is this:
//   they are not three facts. They are one frequency distribution, read at
//   different ORDERS and different GRANULARITIES. In particular —
//
//     The index of coincidence IS a Shannon-cousin of the entropy.
//     For the single-letter distribution p over 26 letters:
//        H1(p) = −Σ p_i log2 p_i              (Shannon entropy — Rényi ORDER 1)
//        IC(p) = Σ p_i²                        (index of coincidence)
//        H2(p) = −log2 Σ p_i² = −log2 IC       (collision / Rényi ORDER 2 entropy)
//     so   IC = 2^(−H2)   — EXACTLY, to machine precision.
//   The cipher's "0.066" and the entropy stratum's "4.1 bits" are the SAME
//   distribution measured at α = 2 and α = 1. The Rényi family H_α is
//   non-increasing in α, and every H_α equals the ceiling log2(26) if and only
//   if the language is uniform. "English is lumpy" is exactly: H_α < ceiling
//   for every α > 0. Each instrument is one reading of that one inequality.
//
//   Zipf is the same skew one floor up — at the WORD level instead of the
//   letter level: a rank-frequency distribution whose Shannon entropy sits far
//   below its own uniform ceiling, with the famous slope ≈ −1 on log-log axes.
//
//   And Shannon's headline (~1 bit/letter, ~75% redundancy) is the same
//   lumpiness compounded across CONTEXT — the part single-letter IC cannot see.
//   So the portal's spine is a ladder: order (α: 1 vs 2), then granularity
//   (letters → words → context).
//
// SOURCES (verified against the member strata and their primary corpora):
//   Shannon, C.E. (1951) "Prediction and Entropy of Printed English", BSTJ 30:50.
//     27-symbol F1 = 4.03; redundancy "roughly 75%".
//   Rényi, A. (1961) "On measures of entropy and information", 4th Berkeley Symp.
//     H_α = (1/(1−α)) log Σ p_i^α; non-increasing in α; α=2 is collision entropy.
//   Friedman, W.F. (Riverbank Pub. 22, 1922) — the index of coincidence κ_p.
//   Lewand, R. (2000) Cryptological Mathematics, Table 1.1 (standard frequencies).
//   Zipf, G.K. (1949) Human Behavior and the Principle of Least Effort.
//   Corpora: Frankenstein (Gutenberg #84); Moby-Dick (#2701); Pride and
//     Prejudice (#1342); the complete works of Shakespeare (#100). All PD.
//
// Run:   node research/lumpiness-of-english/verify.mjs
// Emits: research/lumpiness-of-english/artifact.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 ROOT = path.resolve(HERE, '..', '..');
const log2 = (x) => Math.log(x) / Math.LN2;

let pass = 0, fail = 0;
const log = (ok, msg) => { (ok ? pass++ : fail++); console.log(`${ok ? '  ✓' : '  ✗ FAIL'} ${msg}`); };
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;

// ───────────────────────── corpora ─────────────────────────
// Two member strata keep the same texts. We read THEIR committed copies so the
// combine is provably the same data, not a re-fetch that could drift.
const CORPORA = {
  frankenstein: { file: 'research/entropy-of-english/corpora/frankenstein.txt', label: 'Frankenstein — Mary Shelley (Gutenberg #84)' },
  'moby-dick':  { file: 'research/zipfs-law/corpora/moby-dick.txt',             label: 'Moby-Dick — Herman Melville (Gutenberg #2701)' },
  'pride-and-prejudice': { file: 'research/zipfs-law/corpora/pride-and-prejudice.txt', label: 'Pride and Prejudice — Jane Austen (Gutenberg #1342)' },
  shakespeare:  { file: 'research/zipfs-law/corpora/shakespeare.txt',           label: 'Complete Works — Shakespeare (Gutenberg #100)' },
};

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;
}

// ── 26-letter alphabet (the cipher's world): A–Z → 0..25, everything else gone.
function letters26(text) {
  const up = text.toUpperCase();
  const out = [];
  for (let i = 0; i < up.length; i++) {
    const c = up.charCodeAt(i);
    if (c >= 65 && c <= 90) out.push(c - 65);
  }
  return out;
}
// ── 27-symbol alphabet (the entropy stratum's world): A–Z + collapsed space.
function normalize27(text) {
  const up = text.toUpperCase();
  const out = [];
  let lastSpace = true;
  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;
}

// ───────────────────────── measures of one distribution ─────────────────────────
function freqVector(letters, K = 26) {
  const c = new Array(K).fill(0);
  for (const x of letters) c[x]++;
  const n = letters.length;
  return c.map((v) => v / n);
}
const shannonH = (p) => { let h = 0; for (const x of p) if (x > 0) h -= x * log2(x); return h; };     // Rényi α→1
const collisionIC = (p) => p.reduce((a, x) => a + x * x, 0);                                          // Σ p_i²
const renyi = (p, alpha) => {                                                                          // general H_α (bits)
  if (alpha === 1) return shannonH(p);
  const s = p.reduce((a, x) => a + (x > 0 ? Math.pow(x, alpha) : 0), 0);
  return (1 / (1 - alpha)) * log2(s);
};
const hartleyH0 = (p) => log2(p.filter((x) => x > 0).length);                                          // α→0: log support
const minEntropyHinf = (p) => -log2(Math.max(...p));                                                   // α→∞: −log max p
const redundancy = (H, K = 26) => 1 - H / log2(K);

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

// load all corpora once
const corp = {};
for (const [id, { file, label }] of Object.entries(CORPORA)) {
  const raw = fs.readFileSync(path.join(ROOT, file), 'utf8');
  const body = stripGutenberg(raw);
  corp[id] = { label, letters: letters26(body), sym27: normalize27(body) };
}
const FK = corp.frankenstein; // the anchor text

// ── (0) the two ceilings, exact ──────────────────────────────────────────────
const CEIL26 = log2(26), CEIL27 = log2(27);
log(approx(CEIL26, 4.700439718, 1e-6), `ceiling, 26 letters: log2(26) = ${CEIL26.toFixed(4)} bits  (the cipher's uniform world)`);
log(approx(CEIL27, 4.754887502, 1e-6), `ceiling, 27 symbols: log2(27) = ${CEIL27.toFixed(4)} bits  (the entropy stratum's ceiling)`);

// ── (1) tie to you-already-know-the-rest: reproduce its monogram F1 = 4.091 ──
// The entropy stratum reports F1 = 4.0910 over its 27-symbol Frankenstein stream.
const entropyData = JSON.parse(fs.readFileSync(path.join(ROOT, 'research/entropy-of-english/data.json'), 'utf8'));
const F1_27 = shannonH(freqVector(FK.sym27, 27));
log(approx(F1_27, entropyData.ladderFull.F1, 5e-3),
  `reproduce the entropy stratum's monogram: F1(27) = ${F1_27.toFixed(4)} bits vs its ${entropyData.ladderFull.F1.toFixed(4)}`);

// ── (2) the same Frankenstein letters, now over 26 — the bridge distribution ──
const p = freqVector(FK.letters, 26);
const H1 = shannonH(p);                 // Rényi order 1
const IC = collisionIC(p);              // Σ p_i²
const H2 = renyi(p, 2);                 // Rényi order 2 = −log2 IC
log(H1 < CEIL26 && H1 > 4.0, `Frankenstein letters, Shannon H1 (α=1) = ${H1.toFixed(4)} bits  (below ${CEIL26.toFixed(3)} — lumpy)`);
log(IC > 0.060 && IC < 0.070, `Frankenstein letters, index of coincidence IC = ${IC.toFixed(5)}  (English band 0.060–0.070)`);

// ── (3) THE IDENTITY: IC = 2^(−H2), to machine precision ──────────────────────
log(approx(IC, Math.pow(2, -H2), 1e-12),
  `IC = 2^(−H2) EXACTLY: ${IC.toFixed(6)} = 2^(−${H2.toFixed(4)}) = ${Math.pow(2, -H2).toFixed(6)}  (|Δ| < 1e-12)`);
log(approx(H2, -log2(IC), 1e-12),
  `H2 = −log2(IC) = ${H2.toFixed(4)} bits  (the index of coincidence is the order-2 Rényi entropy, re-expressed)`);

// ── (4) the Rényi ladder is non-increasing in α: H0 ≥ H1 ≥ H2 ≥ H∞ ───────────
const H0 = hartleyH0(p), Hinf = minEntropyHinf(p);
const chain = [H0, H1, H2, Hinf];
let mono = true; for (let i = 1; i < chain.length; i++) if (chain[i] > chain[i - 1] + 1e-12) mono = false;
log(mono, `Rényi ladder non-increasing: H0 ${H0.toFixed(3)} ≥ H1 ${H1.toFixed(3)} ≥ H2 ${H2.toFixed(3)} ≥ H∞ ${Hinf.toFixed(3)} bits`);
// a denser sweep, α = 0.5,1,1.5,2,3,5,10 — must be monotone the whole way
const alphas = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 5, 10, 50];
const sweep = alphas.map((a) => ({ alpha: a, H: renyi(p, a) }));
let sweepMono = true; for (let i = 1; i < sweep.length; i++) if (sweep[i].H > sweep[i - 1].H + 1e-9) sweepMono = false;
log(sweepMono, `dense α-sweep monotone over {${alphas.join(', ')}}: ${sweep.map((s) => s.H.toFixed(2)).join(' ≥ ')}`);

// ── (5) equality iff uniform — the floor case, and it reproduces the cipher's
//        "random" baselines (IC = 1/26 = 0.03846; entropy = the ceiling) ──────
const uni = new Array(26).fill(1 / 26);
const uH1 = shannonH(uni), uIC = collisionIC(uni), uH2 = renyi(uni, 2), uHinf = minEntropyHinf(uni);
log(approx(uIC, 1 / 26, 1e-12) && approx(uIC, 0.03846, 5e-5),
  `uniform letters: IC = 1/26 = ${uIC.toFixed(5)}  (matches the cipher's random baseline 0.03846)`);
log(approx(uH1, CEIL26, 1e-12) && approx(uH2, CEIL26, 1e-12) && approx(uHinf, CEIL26, 1e-12),
  `uniform: every Rényi order collapses to the ceiling — H1=H2=H∞=${uH1.toFixed(4)} (equality ⇔ uniform)`);

// ── (6) reproduce the cipher's table value: IC from Lewand frequencies = 0.0655 ─
// Lewand (2000) Table 1.1, standard English letter frequencies, in percent A..Z.
const LEWAND = [8.167,1.492,2.782,4.253,12.702,2.228,2.015,6.094,6.966,0.153,0.772,4.025,2.406,6.749,7.507,1.929,0.095,5.987,6.327,9.056,2.758,0.978,2.360,0.150,1.974,0.074];
const pL = LEWAND.map((x) => x / 100);
const sumL = pL.reduce((a, b) => a + b, 0);
const icL = collisionIC(pL);
const icArtifact = JSON.parse(fs.readFileSync(path.join(ROOT, 'research/index-of-coincidence/artifact.json'), 'utf8'));
log(approx(sumL, 1, 2e-3), `Lewand table sums to ${(sumL * 100).toFixed(2)}%  (a rounding-consistent distribution)`);
log(approx(icL, icArtifact.ic.englishKappaP_fromTable, 5e-4),
  `IC from the Lewand table = ${icL.toFixed(4)}  (matches the cipher stratum's ${icArtifact.ic.englishKappaP_fromTable})`);

// ── (7) the lumpiness is the LANGUAGE's, not the book's: IC & H1 stable across
//        four authors, two centuries — small spread is the verified fingerprint ─
const perCorpus = {};
for (const [id, c] of Object.entries(corp)) {
  const q = freqVector(c.letters, 26);
  perCorpus[id] = {
    label: c.label, letters: c.letters.length,
    IC: collisionIC(q), H1: shannonH(q), H2: renyi(q, 2),
    H0: hartleyH0(q), Hinf: minEntropyHinf(q),
    R1: redundancy(shannonH(q)), R2: redundancy(renyi(q, 2)),
    freq: q,
  };
}
const ics = Object.values(perCorpus).map((x) => x.IC);
const icMean = ics.reduce((a, b) => a + b, 0) / ics.length;
const icSpread = Math.max(...ics) - Math.min(...ics);
log(icSpread < 0.006, `IC across 4 authors: [${ics.map((x) => x.toFixed(4)).join(', ')}] — spread ${icSpread.toFixed(4)} (a language fingerprint, mean ${icMean.toFixed(4)})`);
// the identity holds for every corpus, not just the anchor
let allId = true; for (const x of Object.values(perCorpus)) if (!approx(x.IC, Math.pow(2, -x.H2), 1e-12)) allId = false;
log(allId, `IC = 2^(−H2) holds for all 4 corpora to machine precision`);
// redundancy is strictly positive at BOTH orders for every corpus; order 2 sees more
let redOK = true; for (const x of Object.values(perCorpus)) if (!(x.R2 > x.R1 && x.R1 > 0)) redOK = false;
log(redOK, `redundancy > 0 at every order, R2 > R1 each corpus (Frankenstein: R1 ${(perCorpus.frankenstein.R1*100).toFixed(1)}% < R2 ${(perCorpus.frankenstein.R2*100).toFixed(1)}%)`);

// ── (8) Zipf — the same skew one floor up, at the word level ──────────────────
// Recompute the rank-frequency slope by OLS on log10(rank) vs log10(freq) over
// the head, and the word distribution's own redundancy. Cross-check the slope
// against the Zipf stratum's committed sOLS.
function wordCounts(text) {
  const m = new Map();
  const toks = text.toLowerCase().match(/[a-z']+/g) || [];
  for (const w of toks) m.set(w, (m.get(w) || 0) + 1);
  return [...m.entries()].sort((a, b) => b[1] - a[1]);
}
function zipfSlope(ranked, headN = 1000) {
  const N = Math.min(headN, ranked.length);
  let sx = 0, sy = 0, sxx = 0, sxy = 0;
  for (let r = 1; r <= N; r++) {
    const x = Math.log10(r), y = Math.log10(ranked[r - 1][1]);
    sx += x; sy += y; sxx += x * x; sxy += x * y;
  }
  const slope = (N * sxy - sx * sy) / (N * sxx - sx * sx);
  return -slope; // report the positive exponent
}
const zipfData = JSON.parse(fs.readFileSync(path.join(ROOT, 'research/zipfs-law/data.json'), 'utf8'));
const mdRaw = fs.readFileSync(path.join(ROOT, CORPORA['moby-dick'].file), 'utf8');
const mdRanked = wordCounts(stripGutenberg(mdRaw));
const s = zipfSlope(mdRanked, 1000);
log(s > 0.9 && s < 1.25, `Zipf slope (Moby-Dick, OLS over top 1000 words) = ${s.toFixed(3)}  (≈ 1: frequency ∝ 1/rank)`);
log(Math.abs(s - zipfData.corpora['moby-dick'].sOLS) < 0.15,
  `consistent with the Zipf stratum's committed sOLS = ${zipfData.corpora['moby-dick'].sOLS.toFixed(3)}`);
// the word distribution is itself far below its uniform ceiling — same signature
const types = mdRanked.length, total = mdRanked.reduce((a, b) => a + b[1], 0);
const pw = mdRanked.map(([, f]) => f / total);
const Hword = shannonH(pw), Hwordmax = log2(types), Rword = 1 - Hword / Hwordmax;
log(Rword > 0.10 && Hword < Hwordmax,
  `Moby-Dick words: H = ${Hword.toFixed(2)} bits vs uniform ceiling log2(${types}) = ${Hwordmax.toFixed(2)} → redundancy ${(Rword*100).toFixed(0)}% (the skew, in bits)`);

// ── (9) the deeper layer: context. The entropy stratum's own ladder shows the
//        lumpiness compounding (F1 > F2 > F3); IC, a single-letter statistic,
//        is blind to it. We assert the ordering from the committed data. ───────
const L = entropyData.ladderFull;
log(L.F1 > L.F2 && L.F2 > L.F3,
  `context compounds the lumpiness: F1 ${L.F1.toFixed(2)} > F2 ${L.F2.toFixed(2)} > F3 ${L.F3.toFixed(2)} bits (single-letter IC cannot see this)`);
log(entropyData.shannonPublished.redundancyPct === 75,
  `Shannon's long-range redundancy ≈ ${entropyData.shannonPublished.redundancyPct}% (cited, not recomputed here — the destination IC only starts)`);

// ───────────────────────── emit artifact ─────────────────────────
const round = (x, n = 6) => Number(x.toFixed(n));
// A STABLE STAMP. This used to be `new Date().toISOString()`, unconditionally, so merely
// running the verifier rewrote artifact.json and left the working tree dirty: same
// payload, new 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.
// 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 artifact = {
  generatedBy: 'research/lumpiness-of-english/verify.mjs',
  generated: null, // filled below, from stableStamp
  thesis: 'IC = 2^(-H2): the index of coincidence is the order-2 Rényi entropy of the single-letter distribution; Shannon entropy is order 1; Zipf is the same skew at word level. One distribution, three instruments.',
  ceilings: { letters26: round(CEIL26), symbols27: round(CEIL27) },
  anchor: {
    corpus: 'Frankenstein', letters: FK.letters.length,
    F1_27_reproduced: round(F1_27), F1_27_stratum: round(entropyData.ladderFull.F1),
    H1: round(H1), IC: round(IC, 6), H2: round(H2),
    H0: round(H0), Hinf: round(Hinf),
    identity_IC_eq_2powMinusH2: round(Math.pow(2, -H2), 6),
    R1: round(redundancy(H1)), R2: round(redundancy(H2)),
    freq26: p.map((x) => round(x, 6)),
  },
  uniform: { IC: round(uIC, 6), H1: round(uH1), H2: round(uH2), Hinf: round(uHinf) },
  lewand: { table_pct: LEWAND, IC: round(icL, 6), matchesCipher: icArtifact.ic.englishKappaP_fromTable },
  renyiSweep: sweep.map((s) => ({ alpha: s.alpha, H: round(s.H) })),
  perCorpus: Object.fromEntries(Object.entries(perCorpus).map(([k, v]) => [k, {
    label: v.label, letters: v.letters,
    IC: round(v.IC, 6), H1: round(v.H1), H2: round(v.H2), H0: round(v.H0), Hinf: round(v.Hinf),
    R1: round(v.R1), R2: round(v.R2), freq26: v.freq.map((x) => round(x, 6)),
  }])),
  icAcrossCorpora: { values: ics.map((x) => round(x, 6)), mean: round(icMean, 6), spread: round(icSpread, 6) },
  zipf: {
    corpus: 'Moby-Dick', slopeOLS_top1000: round(s, 4), stratum_sOLS: round(zipfData.corpora['moby-dick'].sOLS, 4),
    types, tokens: total, Hword: round(Hword), HwordMax: round(Hwordmax), Rword: round(Rword),
    head: mdRanked.slice(0, 12).map(([w, f]) => ({ w, f })),
  },
  context: { F1: round(L.F1), F2: round(L.F2), F3: round(L.F3), longRangeRedundancyPct: entropyData.shannonPublished.redundancyPct },
  members: ['you-already-know-the-rest', 'the-cipher-couldnt-hide', 'the-law-even-monkeys-obey'],
};

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