#!/usr/bin/env node
// Verifier for the stratum "What the Cipher Couldn't Hide"
//   page: src/content/strata/the-cipher-couldnt-hide.md (wrapped markdown)
//   live: https://artwaste.land/strata/the-cipher-couldnt-hide/
//
// The whole stratum rests on one measurable fact: a monoalphabetic substitution
// PRESERVES a language's index of coincidence (it only permutes the letters), so
// it cannot hide how "lumpy" the letter distribution is — while a polyalphabetic
// (Vigenère) cipher FLATTENS that lumpiness toward random in an amount that, run
// backwards, hands you the key length and then the key itself. This script proves
// every number the page prints, end to end:
//
//   1. the index of coincidence (IC) of random text  → 1/26 = 0.03846…
//   2. the IC of English, computed from a real frequency table          (κ_p)
//   3. IC is INVARIANT under any monoalphabetic substitution            (the moat)
//   4. a worked Vigenère break of a composed English passage:
//        - the whole-ciphertext IC collapses toward random
//        - the Friedman/κ key-length estimate
//        - Kasiski examination: repeated trigrams → distances → key length
//        - per-coset IC: the true key length (and its multiples) light up English
//        - χ² key recovery, coset by coset → the exact key
//        - decryption reproduces the plaintext byte for byte
//
// The plaintext is COMPOSED for this demonstration (English prose I wrote), so no
// claim here depends on quoting any external text accurately; every assertion is
// about the statistics and the algorithm, which this file controls. Historical
// facts in the prose (Bellaso 1553, Babbage ~1854, Kasiski 1863, Friedman 1922)
// carry their own citations in the stratum's sources; they are not asserted here.
//
// Run:  node research/index-of-coincidence/verify.mjs
// Exit: 0 if every check passes, 1 otherwise. No dependencies (Node 18+).

import { writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

let pass = 0, fail = 0;
function check(label, cond, got) {
  if (cond) { pass++; console.log(`  ok   ${label}`); }
  else { fail++; console.log(`  FAIL ${label}` + (got !== undefined ? `  (got: ${JSON.stringify(got)})` : "")); }
}
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
const A = "A".charCodeAt(0);
const onlyAZ = (s) => s.toUpperCase().replace(/[^A-Z]/g, "");
const round = (x, n = 5) => Number(x.toFixed(n));

// ---------------------------------------------------------------------------
// English letter frequencies (relative, %). Source: standard concordance figures
// widely tabulated from large English corpora (e.g. Lewand, "Cryptological
// Mathematics", 2000, Table 1.1). Used only to (a) compute the English IC and
// (b) score candidate Caesar shifts in key recovery. The break does NOT depend
// on these being exact — χ² recovery is robust to small table differences.
const FREQ = {
  A: 8.167, B: 1.492, C: 2.782, D: 4.253, E: 12.702, F: 2.228, G: 2.015,
  H: 6.094, I: 6.966, J: 0.153, K: 0.772, L: 4.025, M: 2.406, N: 6.749,
  O: 7.507, P: 1.929, Q: 0.095, R: 5.987, S: 6.327, T: 9.056, U: 2.758,
  V: 0.978, W: 2.360, X: 0.150, Y: 1.974, Z: 0.074,
};
const FREQ_P = Object.fromEntries(Object.entries(FREQ).map(([k, v]) => [k, v / 100]));

// ---------------------------------------------------------------------------
// Index of coincidence.
//   IC = Σ n_i (n_i − 1) / [ N (N − 1) ]
// = the probability that two letters drawn without replacement are equal.
function indexOfCoincidence(text) {
  const t = onlyAZ(text);
  const N = t.length;
  if (N < 2) return 0;
  const counts = new Array(26).fill(0);
  for (const ch of t) counts[ch.charCodeAt(0) - A]++;
  let num = 0;
  for (const n of counts) num += n * (n - 1);
  return num / (N * (N - 1));
}

// Letter counts helper.
function counts(text) {
  const c = new Array(26).fill(0);
  for (const ch of onlyAZ(text)) c[ch.charCodeAt(0) - A]++;
  return c;
}

// ---------------------------------------------------------------------------
// Vigenère encrypt / decrypt (letters only; passthrough handled by caller).
function vigenere(text, key, decrypt = false) {
  const k = onlyAZ(key);
  let out = "", ki = 0;
  for (const ch of text) {
    const up = ch.toUpperCase();
    if (up >= "A" && up <= "Z") {
      const shift = k.charCodeAt(ki % k.length) - A;
      const p = up.charCodeAt(0) - A;
      const c = decrypt ? (p - shift + 26) % 26 : (p + shift) % 26;
      out += String.fromCharCode(A + c);
      ki++;
    } else {
      out += ch; // preserve spacing/punctuation in the readable rendering
    }
  }
  return out;
}

// Caesar shift a coset by s (used in key recovery scoring).
const shiftBack = (s, str) =>
  str.replace(/[A-Z]/g, (ch) => String.fromCharCode(A + (ch.charCodeAt(0) - A - s + 26) % 26));

console.log("\nWhat the Cipher Couldn't Hide — verifier\n");

// === 1. IC of random text → 1/26 ==========================================
console.log("§1  IC of uniformly random text → 1/26");
{
  // Deterministic LCG so the figure the page prints is reproducible.
  let seed = 1234567;
  const rng = () => (seed = (1103515245 * seed + 12345) % 2147483648) / 2147483648;
  let rand = "";
  const Nrand = 100000;
  for (let i = 0; i < Nrand; i++) rand += String.fromCharCode(A + Math.floor(rng() * 26));
  const icRand = indexOfCoincidence(rand);
  const expected = 1 / 26;
  check(`1/26 = ${round(expected)}`, approx(expected, 0.03846, 1e-5), round(expected));
  check(`100k random letters: IC ≈ 1/26 (got ${round(icRand)})`, approx(icRand, expected, 0.002), round(icRand));
}

// === 2. IC of English from the frequency table ============================
console.log("\n§2  IC of English (Σ pᵢ²) from the frequency table");
let kappaP;
{
  // For an idealised long English text, IC → Σ pᵢ². This is Friedman's κ_p.
  kappaP = Object.values(FREQ_P).reduce((s, p) => s + p * p, 0);
  const probSum = Object.values(FREQ_P).reduce((s, p) => s + p, 0);
  check(`frequency table sums to 1 (got ${round(probSum, 4)})`, approx(probSum, 1, 0.005), round(probSum, 4));
  check(`κ_p = Σpᵢ² ≈ 0.0655–0.0667 (got ${round(kappaP)})`, kappaP > 0.064 && kappaP < 0.0675, round(kappaP));
  // E is the spike that makes English "lumpy": p_E² alone exceeds the whole
  // random IC contribution of any single letter (1/26² = 0.00148).
  check(`E alone (p_E² = ${round(FREQ_P.E ** 2)}) > random per-letter (1/26² = ${round((1/26)**2)})`,
        FREQ_P.E ** 2 > (1/26) ** 2, round(FREQ_P.E ** 2));
}

// === 3. IC is INVARIANT under monoalphabetic substitution =================
console.log("\n§3  monoalphabetic substitution preserves IC (the moat)");
let plaintext, icPlain;
{
  // The composed demonstration plaintext (English prose, written for this demo).
  plaintext =
    "The strength of a cipher was once thought to live entirely in its secrecy, " +
    "as though a method kept hidden could never be undone by a patient stranger. " +
    "But a language leaves a fingerprint that no simple replacement can wipe away, " +
    "because the letters keep the same uneven weights even after every one of them " +
    "has been traded for another symbol. The vowel that arrives most often in plain " +
    "speech still arrives most often in the disguise, merely wearing a different mask. " +
    "Only when each letter is allowed to change its mask from one position to the next " +
    "does the telltale unevenness begin to smooth away, and even then the smoothing is " +
    "never quite complete, for the rhythm of the shifting key prints a fainter pattern " +
    "of its own across the message, a pattern a careful reader can measure and unwind.";
  icPlain = indexOfCoincidence(plaintext);

  // A fixed, arbitrary permutation of the alphabet (a monoalphabetic key).
  const SUB = "QWERTYUIOPASDFGHJKLZXCVBNM"; // A→Q, B→W, …
  const substitute = (t) =>
    t.toUpperCase().replace(/[A-Z]/g, (ch) => SUB[ch.charCodeAt(0) - A]);
  const subbed = substitute(plaintext);
  const icSub = indexOfCoincidence(subbed);

  check(`plaintext IC is English-like (got ${round(icPlain)})`, icPlain > 0.055 && icPlain < 0.08, round(icPlain));
  check(`substituted text has IDENTICAL IC (${round(icSub)})`, approx(icPlain, icSub, 1e-12), round(icSub));
  // And the sorted frequency multiset is identical — substitution only relabels.
  const sortedMultiset = (t) => counts(t).filter((n) => n).sort((a, b) => a - b).join(",");
  check(`sorted frequency multiset identical under substitution`,
        sortedMultiset(plaintext) === sortedMultiset(subbed));
}

// === 4. A worked Vigenère break ===========================================
console.log("\n§4  breaking Vigenère by the index of coincidence");
const KEY = "FRIEDMAN"; // 8 letters, named for the index's author
const L_true = KEY.length;
const ciphertext = vigenere(plaintext, KEY);
const Pletters = onlyAZ(plaintext);
const Cletters = onlyAZ(ciphertext);
const N = Cletters.length;
check(`ciphertext preserves letter count (N = ${N})`, N === Pletters.length, N);

// --- 4a. whole-ciphertext IC collapses toward random ----------------------
const icCipher = indexOfCoincidence(ciphertext);
check(`whole-ciphertext IC (${round(icCipher)}) collapsed well below plaintext (${round(icPlain)})`,
      icCipher < icPlain - 0.01, round(icCipher));
check(`whole-ciphertext IC sits between random and English`,
      icCipher > 1 / 26 - 0.005 && icCipher < kappaP, round(icCipher));

// --- 4b. Friedman key-length estimate -------------------------------------
// Friedman's finite-N estimate, derived from the expected whole-text IC under a
// key of length L:
//     E[κ_o] = (N−L)/(L(N−1))·κ_p + N(L−1)/(L(N−1))·κ_r
// Solving for L:
//     L̂ = N(κ_p − κ_r) / [ κ_o(N−1) + κ_p − N·κ_r ]
// κ_r = 1/26; κ_p is the canonical English IC a cryptanalyst plugs in (0.0667,
// Friedman's value — our own table gives 0.0655, see §2). HONEST LIMITATION:
// the signal here is κ_o − κ_r, only ~0.0015 for a key this long, so on a short
// message the estimate is wildly noisy and biased high — it OVERSHOOTS 8 badly.
// It is a divining rod, not a ruler: it tells you the cipher is polyalphabetic
// with a multi-letter key (L̂ ≫ 1, not ≈ 1), and the coset scan below does the
// actual measuring. We assert exactly that — the rod points the right way.
const kappaR = 1 / 26;
const kappaPcanonical = 0.0667;
const friedmanEstimate =
  N * (kappaPcanonical - kappaR) / (icCipher * (N - 1) + kappaPcanonical - N * kappaR);
check(`Friedman L̂ = ${round(friedmanEstimate, 2)} correctly rules out monoalphabetic (L̂ ≫ 1)`,
      friedmanEstimate > 3, round(friedmanEstimate, 2));
check(`Friedman L̂ overshoots the true 8 on this short message (the documented limitation)`,
      friedmanEstimate > L_true, round(friedmanEstimate, 2));

// --- 4c. Kasiski examination ----------------------------------------------
// Repeated substrings in the CIPHERTEXT tend to come from the same plaintext
// aligned with the same stretch of key; the gap between repeats is then a
// multiple of the key length. Collect gaps, factor them, and the key length
// shows up as the most common shared factor.
function kasiskiGaps(text, len = 3) {
  const t = onlyAZ(text);
  const seen = new Map();
  const gaps = [];
  for (let i = 0; i + len <= t.length; i++) {
    const g = t.slice(i, i + len);
    if (seen.has(g)) gaps.push(i - seen.get(g));
    seen.set(g, i);
  }
  return gaps;
}
const gaps = kasiskiGaps(ciphertext, 3);
// Tally which candidate lengths divide the most gaps.
const factorVotes = new Map();
for (let f = 2; f <= 16; f++) {
  let v = 0;
  for (const g of gaps) if (g % f === 0) v++;
  factorVotes.set(f, v);
}
// The true key length should divide a strong plurality of the gaps.
const votesForTrue = factorVotes.get(L_true);
check(`Kasiski: ${gaps.length} repeated-trigram gaps found`, gaps.length >= 3, gaps.length);
check(`Kasiski: key length ${L_true} divides a majority of gaps (${votesForTrue}/${gaps.length})`,
      gaps.length > 0 && votesForTrue / gaps.length >= 0.5, `${votesForTrue}/${gaps.length}`);

// --- 4d. per-coset IC: the true length (and multiples) light up English ---
// Split the ciphertext into L cosets (positions ≡ r mod L). If L is the true
// key length, every coset is a pure Caesar shift of English → IC ≈ κ_p. If L is
// wrong, the cosets are still polyalphabetic mixtures → IC ≈ random.
function cosetMeanIC(text, L) {
  const t = onlyAZ(text);
  const cos = Array.from({ length: L }, () => "");
  for (let i = 0; i < t.length; i++) cos[i % L] += t[i];
  let s = 0;
  for (const c of cos) s += indexOfCoincidence(c);
  return s / L;
}
const cosetTable = {};
for (let L = 1; L <= 16; L++) cosetTable[L] = round(cosetMeanIC(ciphertext, L));
// The true length must read English-like; the lengths just below it must not.
check(`coset-IC at L=${L_true} is English-like (${cosetTable[L_true]})`, cosetTable[L_true] > 0.058, cosetTable[L_true]);
for (const L of [5, 6, 7]) {
  check(`coset-IC at wrong L=${L} stays near random (${cosetTable[L]})`, cosetTable[L] < 0.050, cosetTable[L]);
}
// And L=8 should be the smallest L whose coset-IC clears an English threshold.
const firstEnglish = Object.keys(cosetTable).map(Number).sort((a, b) => a - b)
  .find((L) => cosetTable[L] > 0.058);
check(`smallest English-like coset length is exactly ${L_true} (got ${firstEnglish})`, firstEnglish === L_true, firstEnglish);

// --- 4e. χ² key recovery, coset by coset ----------------------------------
// For each coset, try all 26 un-shifts; the shift whose letter distribution best
// matches English (lowest χ²) is the key letter for that position.
function bestShift(coset) {
  const cN = coset.length;
  const cc = counts(coset);
  let best = 0, bestChi = Infinity;
  for (let s = 0; s < 26; s++) {
    let chi = 0;
    for (let i = 0; i < 26; i++) {
      const observed = cc[(i + s) % 26];           // letter i of plaintext appears here
      const expected = FREQ_P[String.fromCharCode(A + i)] * cN;
      chi += (observed - expected) ** 2 / (expected || 1e-9);
    }
    if (chi < bestChi) { bestChi = chi; best = s; }
  }
  return best;
}
let recoveredKey = "";
{
  const t = Cletters;
  const cos = Array.from({ length: L_true }, () => "");
  for (let i = 0; i < t.length; i++) cos[i % L_true] += t[i];
  for (const c of cos) recoveredKey += String.fromCharCode(A + bestShift(c));
}
check(`χ² recovers the key exactly: "${recoveredKey}" == "${KEY}"`, recoveredKey === KEY, recoveredKey);

// --- 4f. decryption reproduces the plaintext ------------------------------
// Encryption forces letters to uppercase (a cryptanalyst never sees the original
// case), so the honest claim is that the recovered LETTERS match the plaintext's.
const decrypted = vigenere(ciphertext, recoveredKey, true);
check(`decryption with the recovered key reproduces every plaintext letter`,
      onlyAZ(decrypted) === Pletters);
check(`recovered key decrypts to readable English (first 40 letters)`,
      onlyAZ(decrypted).slice(0, 40) === Pletters.slice(0, 40), onlyAZ(decrypted).slice(0, 40));

// === artifact =============================================================
const artifact = {
  generatedBy: "research/index-of-coincidence/verify.mjs",
  ic: {
    random: round(1 / 26),
    englishKappaP_fromTable: round(kappaP),
    englishKappaP_canonical: kappaPcanonical,
    plaintext: round(icPlain),
    ciphertext: round(icCipher),
  },
  break: {
    key: KEY,
    keyLength: L_true,
    plaintextLetters: N,
    friedmanEstimate: round(friedmanEstimate, 2),
    friedmanNote: "overshoots on short text — a divining rod, not a ruler; the coset scan does the measuring",
    kasiskiGaps: gaps.length,
    kasiskiVotesForTrueLength: `${votesForTrue}/${gaps.length}`,
    cosetMeanIC: cosetTable,
    smallestEnglishLikeCosetLength: firstEnglish,
    recoveredKey,
    decryptionExact: onlyAZ(decrypted) === Pletters,
  },
  freqTableSource: "Lewand, Cryptological Mathematics (2000), Table 1.1 (standard English letter frequencies)",
};
const here = dirname(fileURLToPath(import.meta.url));
writeFileSync(join(here, "artifact.json"), JSON.stringify(artifact, null, 2) + "\n");

console.log(`\n  artifact → research/index-of-coincidence/artifact.json`);
console.log(`\n${pass}/${pass + fail} checks passed${fail ? `, ${fail} FAILED` : ""}.\n`);
process.exit(fail ? 1 : 0);
