#!/usr/bin/env node
// Verifier for the COMBINE stratum "The Invariant of Relabeling"
//   page: src/content/strata/the-invariant-of-relabeling.md (immersive)
//   live: public/strata/the-invariant-of-relabeling/index.html
//   joins: "What the Cipher Couldn't Hide" (research/index-of-coincidence/)
//          "The Grid That Spoke Greek"      (research/the-grid-that-spoke-greek/)
//
// The page compares two models of structure preserved by relabeling.
//
// CIPHER. An unrestricted monoalphabetic substitution has 26! possible keys.
// IC depends only on the multiset of letter counts and is invariant under all
// of those substitutions. Vigenere is narrower: each known-period column uses
// one of 26 Caesar shifts. Frequency scoring is one way to identify a shift;
// a known plaintext/ciphertext letter pair also determines it.
//
// GRID. In a complete r by c consonant/vowel toy, the permutations preserving
// both row and column relations number r! times c!. In the 3 by 3 example one
// pin leaves four assignments and two pins in distinct rows and columns leave
// one. This models constraint propagation, not the full 1952 decipherment,
// which used structural analysis together with phonetic and place-name guesses.
//
// These checks independently recompute the cipher and toy-grid results from
// embedded data. They do not read the page or validate its historical prose.
// Node built-ins only (Node 18+).
//
// Run:  node research/invariant-of-relabeling/verify.mjs
// Exit: 0 if every check passes, 1 otherwise.

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 round = (x, n = 5) => Number(x.toFixed(n));
const A = "A".charCodeAt(0);
const onlyAZ = (s) => s.toUpperCase().replace(/[^A-Z]/g, "");

// ---------------------------------------------------------------------------
// Index of coincidence (same definition the cipher stratum verifies):
//   IC = Σ n_i (n_i − 1) / [ N (N − 1) ] = P(two letters drawn alike).
function indexOfCoincidence(text) {
  const t = onlyAZ(text);
  const N = t.length;
  if (N < 2) return 0;
  const c = new Array(26).fill(0);
  for (const ch of t) c[ch.charCodeAt(0) - A]++;
  let num = 0;
  for (const n of c) num += n * (n - 1);
  return num / (N * (N - 1));
}
function counts(text) {
  const c = new Array(26).fill(0);
  for (const ch of onlyAZ(text)) c[ch.charCodeAt(0) - A]++;
  return c;
}
const sortedMultiset = (t) => counts(t).slice().sort((a, b) => a - b).join(",");

// Deterministic RNG so every figure is reproducible.
function lcg(seed) {
  let s = seed >>> 0;
  return () => (s = (1103515245 * s + 12345) % 2147483648) / 2147483648;
}
// A uniformly random permutation of A..Z (a monoalphabetic key), from a seed.
function randomKey(rng) {
  const a = [...Array(26).keys()];
  for (let i = 25; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
  return a.map((n) => String.fromCharCode(A + n)).join("");
}
const substitute = (t, key) =>
  t.toUpperCase().replace(/[A-Z]/g, (ch) => key[ch.charCodeAt(0) - A]);

// Vigenère (letters only; spacing preserved for readability).
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;
      out += String.fromCharCode(A + (decrypt ? (p - shift + 26) % 26 : (p + shift) % 26));
      ki++;
    } else out += ch;
  }
  return out;
}
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];
  return cos.reduce((s, c) => s + indexOfCoincidence(c), 0) / L;
}

// The demonstration plaintext is composed prose, preserved as the exact cipher
// input the page ships. Its closing single-name sufficiency claim is an overclaim;
// the page explains it beside the quotation. These checks validate the numbers,
// not that sentence's account of decipherment.
const PLAINTEXT =
  "A cipher can change which letter wears which mask, but it cannot change how " +
  "often the masks recur, and that stubborn unevenness is a fingerprint no costume " +
  "can hide. A script is stranger still, for there both the masks and the language " +
  "behind them are unknown, and yet the same handle is there to be seized: the way " +
  "the signs lean on one another holds its shape no matter what sounds we later give " +
  "them. So we read the structure first and the meaning second, and one lucky guess " +
  "at a single name is enough to make the whole arrangement speak aloud at last.";

console.log("\nThe Invariant of Relabeling — verifier\n");

// === 1. the two reference values the page prints ==========================
console.log("§1  the random floor and the English ceiling");
{
  const rng = lcg(20260619);
  let rand = "";
  for (let i = 0; i < 100000; i++) rand += String.fromCharCode(A + Math.floor(rng() * 26));
  const icRand = indexOfCoincidence(rand);
  check(`random floor 1/26 = ${round(1 / 26)}`, approx(1 / 26, 0.03846, 1e-5), round(1 / 26));
  check(`100k random letters land on the floor (got ${round(icRand)})`, approx(icRand, 1 / 26, 0.002), round(icRand));
  const icPlain = indexOfCoincidence(PLAINTEXT);
  check(`the demo passage is English-lumpy (IC ${round(icPlain)} ≫ floor)`, icPlain > 0.058 && icPlain < 0.085, round(icPlain));
}

// === 2. the moat: IC is invariant over ALL 26! relabelings ================
// We can't enumerate 26! keys, but invariance is structural: IC depends only on
// the sorted frequency multiset, which any relabeling merely permutes. We prove
// it the way a skeptic would accept — a large random battery of distinct keys,
// every one giving the IDENTICAL IC and the IDENTICAL sorted multiset.
console.log("\n§2  the moat — every one of the 26! relabelings leaves IC fixed");
{
  const icPlain = indexOfCoincidence(PLAINTEXT);
  const msPlain = sortedMultiset(PLAINTEXT);
  const rng = lcg(7);
  let allEqual = true, allMultiset = true;
  const seen = new Set();
  for (let i = 0; i < 500; i++) {
    const key = randomKey(rng);
    seen.add(key);
    const sub = substitute(PLAINTEXT, key);
    if (!approx(indexOfCoincidence(sub), icPlain, 1e-12)) allEqual = false;
    if (sortedMultiset(sub) !== msPlain) allMultiset = false;
  }
  check(`500 distinct random keys tried (got ${seen.size} unique)`, seen.size === 500, seen.size);
  check(`IC identical to 1e-12 under every one of them`, allEqual);
  check(`the sorted frequency "shape" is identical under every one of them`, allMultiset);
  // It is the SHAPE, not the labels: the alphabetical histogram is permuted, the
  // sorted histogram is fixed. Confirm a substitution really does move the labels.
  const movedLabels = substitute(PLAINTEXT, randomKey(lcg(99))) !== PLAINTEXT.toUpperCase();
  check(`a substitution really does move the labels (it isn't a no-op)`, movedLabels);
}

// === 3. polyalphabetic flattening, and the period it can't hide ===========
console.log("\n§3  hide the shape with L alphabets — the period stays visible");
const KEY = "VENTRIS"; // 7 letters — the man who broke Linear B, hiding the cipher
const L_true = KEY.length;
const ciphertext = vigenere(PLAINTEXT, KEY);
{
  const icPlain = indexOfCoincidence(PLAINTEXT);
  const icCipher = indexOfCoincidence(ciphertext);
  check(`whole-ciphertext IC (${round(icCipher)}) collapsed toward the floor`,
    icCipher < icPlain - 0.01 && icCipher > 1 / 26 - 0.006, round(icCipher));
  // Coset scan: the fundamental period and its multiples use single shifts;
  // nonmultiples generally mix alphabets.
  const table = {};
  for (let L = 1; L <= 14; L++) table[L] = round(cosetMeanIC(ciphertext, L));
  check(`coset-IC at the true L=${L_true} reads English (${table[L_true]})`, table[L_true] > 0.055, table[L_true]);
  const firstEnglish = Object.keys(table).map(Number).sort((a, b) => a - b).find((L) => table[L] > 0.055);
  check(`the smallest English-like coset length is exactly ${L_true}`, firstEnglish === L_true, firstEnglish);
  for (const L of [4, 5, 6]) check(`a wrong L=${L} stays near the floor (${table[L]})`, table[L] < 0.050, table[L]);
}

// === 4. the grid's symmetry is r!·c!, constrained by anchors ==============
// A precise toy of Kober's deduction. Model a syllabary as an r×c grid: each sign
// is a (consonant-row, vowel-column) cell. The two relations she recovered with
// NO sound values — SAME-CONSONANT (same row) and SAME-VOWEL (same column) — are
// the structure. The relabelings that preserve BOTH relations are exactly: permute
// the rows among themselves (rename the consonants) and the columns among themselves
// (rename the vowels). So the structure alone fixes the grid up to r!·c! choices of
// sound — the "residual symmetry." A place-name pins specific signs to specific
// sounds; each independent pin in a fresh row AND column divides the freedom.
//
// We count the symmetry by BRUTE FORCE — every permutation of the signs that
// preserves the two relations — and confirm it equals r!·c!, then watch anchors
// collapse it. (Brute force keeps the claim honest: no formula is trusted, the
// permutations are enumerated.) The page is explicit that this is a toy model of
// the principle, not a model of the actual 1952 decipherment.
console.log("\n§4  the grid: structure fixes the signs up to r!·c!, anchors constrain it");
function factorial(n) { let f = 1; for (let i = 2; i <= n; i++) f *= i; return f; }
// signs of an r×c grid, indexed 0..rc-1 as cell (row=Math.floor(i/c), col=i%c).
function gridStructure(r, c) {
  const n = r * c;
  const rowOf = (i) => Math.floor(i / c), colOf = (i) => i % c;
  // adjacency for the two relations, as boolean matrices
  const sameRow = (i, j) => rowOf(i) === rowOf(j);
  const sameCol = (i, j) => colOf(i) === colOf(j);
  return { n, rowOf, colOf, sameRow, sameCol };
}
// Count permutations p of {0..n-1} preserving both relations, optionally subject
// to a set of FIXED points (anchors: sign a must map to itself, i.e. keep its sounds).
function countSymmetries(r, c, anchors = []) {
  const { n, sameRow, sameCol } = gridStructure(r, c);
  const perm = new Array(n).fill(-1);
  const used = new Array(n).fill(false);
  const anchorSet = new Map(anchors.map((a) => [a, a]));
  let total = 0;
  function ok(i, val) {
    for (let j = 0; j < i; j++) {
      if (sameRow(i, j) !== sameRow(val, perm[j])) return false;
      if (sameCol(i, j) !== sameCol(val, perm[j])) return false;
    }
    return true;
  }
  (function place(i) {
    if (i === n) { total++; return; }
    if (anchorSet.has(i)) { // anchored sign is forced to a fixed sound (itself)
      const val = anchorSet.get(i);
      if (!used[val] && ok(i, val)) { used[val] = true; perm[i] = val; place(i + 1); used[val] = false; perm[i] = -1; }
      return;
    }
    for (let val = 0; val < n; val++) {
      if (used[val]) continue;
      if (!ok(i, val)) continue;
      used[val] = true; perm[i] = val; place(i + 1); used[val] = false; perm[i] = -1;
    }
  })(0);
  return total;
}
{
  const r = 3, c = 3;
  const sym = countSymmetries(r, c);
  check(`a ${r}×${c} grid's structure leaves exactly r!·c! = ${factorial(r)}·${factorial(c)} = ${factorial(r) * factorial(c)} sound-assignments`,
    sym === factorial(r) * factorial(c), sym);
  // One anchor: pin sign 0 = cell (row0,col0). Its row and column are now named;
  // the rest is (r-1)!·(c-1)! free.
  const sym1 = countSymmetries(r, c, [0]);
  check(`pin ONE sign → (r-1)!·(c-1)! = ${factorial(r - 1) * factorial(c - 1)} remain`,
    sym1 === factorial(r - 1) * factorial(c - 1), sym1);
  // Two anchors in a fresh row AND column (cell (0,0) and (1,1)): names 2 rows + 2
  // cols, leaving (r-2)!·(c-2)! = 1·1 = 1 — the grid is forced.
  const sym2 = countSymmetries(r, c, [0, 4]); // 4 = cell (1,1) for c=3
  check(`pin TWO signs in fresh rows & columns → exactly 1 (the grid is forced)`,
    sym2 === factorial(r - 2) * factorial(c - 2), sym2);
  // Count the actual Vigenere column keys separately from arbitrary substitution.
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const shifts = new Set([...alphabet].map(key => vigenere(alphabet, key)));
  check(`a Vigenere column has 26 shifts; unrestricted substitution has 26!, exceeding the toy's 36`,
    shifts.size === 26 && factorial(26) > sym * 1e10,
    { shifts: shifts.size, toyAssignments: sym });
}

// === artifact =============================================================
const rng = lcg(20260619);
let rand = ""; for (let i = 0; i < 100000; i++) rand += String.fromCharCode(A + Math.floor(rng() * 26));
const table = {}; for (let L = 1; L <= 14; L++) table[L] = round(cosetMeanIC(ciphertext, L));
const artifact = {
  generatedBy: "research/invariant-of-relabeling/verify.mjs",
  thesis: "the models preserve structure under relabeling; anchors constrain the remaining readings",
  cipher: {
    randomFloor: round(1 / 26),
    randomFloorMeasured: round(indexOfCoincidence(rand)),
    plaintextIC: round(indexOfCoincidence(PLAINTEXT)),
    ciphertextIC: round(indexOfCoincidence(ciphertext)),
    vigenereKey: KEY,
    period: L_true,
    cosetMeanIC: table,
    symmetryGroup: "all 26! monoalphabetic relabelings; IC invariant over the whole group",
    anchor: "each known-period Vigenere column has 26 possible shifts; frequency scoring can help identify its shift",
  },
  grid: {
    model: "toy r×c consonant×vowel grid; relations SAME-ROW (consonant) and SAME-COL (vowel)",
    residualSymmetry_3x3: 36,
    formula: "r!·c!",
    afterOneAnchor: 4,
    afterTwoAnchors: 1,
    note: "an illustrative model of Kober's principle, not of the full 1952 decipherment",
  },
};
const here = dirname(fileURLToPath(import.meta.url));
writeFileSync(join(here, "artifact.json"), JSON.stringify(artifact, null, 2) + "\n");
console.log(`\n  artifact → research/invariant-of-relabeling/artifact.json`);
console.log(`\n${pass}/${pass + fail} checks passed${fail ? `, ${fail} FAILED` : ""}.\n`);
process.exit(fail ? 1 : 0);
