#!/usr/bin/env node
// verify.mjs — Conway's audioactive decay, derived and checked from first principles.
//
// Three approaches and a consistency check for one number (Conway's constant λ ≈ 1.3035772690):
//   1. EMPIRICAL: iterate look-and-say from many seeds; the length ratio L(n+1)/L(n) → λ.
//   2. STRUCTURAL: derive Conway's "periodic table" from scratch by finding the permanent
//      split points (walls) of the sequence, confirm it closes to exactly 92 elements,
//      build the 92×92 decay matrix, and take its Perron (largest) eigenvalue.
//   3. ALGEBRAIC: λ is the unique real root > 1 of a degree-71 polynomial (Conway).
//      We locate that root numerically and compare.
//   4. CONSISTENCY: matrix and polynomial agree; measured ratios approach them.
//
// Roads 1 and 2 share the look-and-say operator and seed 1. The checks also use
// published reference digits, polynomial coefficients, and abundance anchors.
// The polynomial is checked against OEIS A137275; Conway's 1987 reprint misprints it.
//
// Run: node research/conway-audioactive/verify.mjs
'use strict';

let PASS = 0, FAIL = 0;
const results = [];
function check(name, cond, detail) {
  if (cond) { PASS++; results.push(['PASS', name, detail]); }
  else { FAIL++; results.push(['FAIL', name, detail]); }
}

// ---------------------------------------------------------------------------
// Core: one look-and-say step ("say what you see").
// ---------------------------------------------------------------------------
function lookAndSay(s) {
  let out = '';
  let i = 0;
  const n = s.length;
  while (i < n) {
    const c = s[i];
    let j = i;
    while (j < n && s[j] === c) j++;
    out += String(j - i) + c;
    i = j;
  }
  return out;
}

// ---------------------------------------------------------------------------
// ROAD 1 — empirical growth ratio.
// ---------------------------------------------------------------------------
function growthRatios(seed, steps) {
  let s = seed;
  const lens = [s.length];
  for (let k = 0; k < steps; k++) { s = lookAndSay(s); lens.push(s.length); }
  const ratios = [];
  for (let k = 1; k < lens.length; k++) ratios.push(lens[k] / lens[k - 1]);
  return { lens, ratios, last: ratios[ratios.length - 1] };
}

// ---------------------------------------------------------------------------
// Splitting: a wall is our name for Conway's permanent splitting boundary.
// The last digit of the left descendant never changes. It suffices to certify
// that every right descendant starts with a different digit.
// Track a complete right string, or a known prefix of it. For a partial prefix,
// discard the last run before deriving: that run may continue beyond the prefix.
// The resulting string is a guaranteed prefix of the next right descendant.
// Repeating a nonempty prefix state proves a cycle whose first digits all avoid
// the left digit. Size and step limits alone never certify a wall; an unresolved
// boundary stays unsplit. Source: Conway, Eureka 46, pp. 6 and 11 (last-digit rule).
// ---------------------------------------------------------------------------
function isWall(left, right) {
  if (!left || !right) return true;
  const last = left[left.length - 1];
  const LIMIT = 64, STEPS = 256;
  let prefix = right.slice(0, LIMIT), complete = right.length <= LIMIT;
  const seen = new Set();
  for (let step = 0; step < STEPS; step++) {
    if (!prefix || prefix[0] === last) return false;
    const state = (complete ? 'full:' : 'prefix:') + prefix;
    if (seen.has(state)) return true;
    seen.add(state);
    let known = prefix;
    if (!complete) {
      let end = known.length - 1;
      while (end > 0 && known[end - 1] === known[known.length - 1]) end--;
      known = known.slice(0, end);
    }
    const next = lookAndSay(known);
    complete = complete && next.length <= LIMIT;
    prefix = next.slice(0, LIMIT);
  }
  return false;
}

// Split a string at certified walls; unresolved boundaries stay within a chunk.
const _splitCache = new Map();
function splitAtoms(s) {
  const hit = _splitCache.get(s);
  if (hit) return hit;
  const atoms = [];
  let start = 0;
  for (let i = 1; i < s.length; i++) {
    if (s[i] !== s[i - 1]) {                 // candidate boundary at a run edge
      if (isWall(s.slice(start, i), s.slice(i))) {
        atoms.push(s.slice(start, i));
        start = i;
      }
    }
  }
  atoms.push(s.slice(start));
  _splitCache.set(s, atoms);
  return atoms;
}

// ---------------------------------------------------------------------------
// ROAD 2 — derive the periodic table.
// An element (atom) = a string with no interior wall. Decay of an atom = split its
// derivative into atoms. We take the closure of decay starting from the atoms that
// appear in the fully-decayed standard sequence (digits 1,2,3 only).
// ---------------------------------------------------------------------------
function derivePeriodicTable() {
  // Bootstrap: decay the seed "1" enough that it has become a compound of atoms,
  // then take the CLOSURE of the decay relation (each atom's derivative, split into
  // atoms). Atoms never interact, so this closure is exactly Conway's periodic table.
  let s = '1';
  for (let i = 0; i < 24; i++) s = lookAndSay(s);   // well past full decay
  const elements = new Set(splitAtoms(s));
  const queue = [...elements];
  const decayOf = new Map();
  while (queue.length) {
    const a = queue.pop();
    if (decayOf.has(a)) continue;
    const kids = splitAtoms(lookAndSay(a));
    decayOf.set(a, kids);
    for (const k of kids) if (!elements.has(k)) { elements.add(k); queue.push(k); }
  }
  return { elements: [...elements], decayOf };
}

// Perron eigenvalue (largest, real, positive) of the decay matrix via power iteration
// on the abundance vector. Convergence is guaranteed by Perron–Frobenius (the decay
// graph is, after restriction to its recurrent part, irreducible with a dominant real λ).
function perronEigenpair(elements, decayOf) {
  const idx = new Map(elements.map((e, i) => [e, i]));
  const n = elements.length;
  // M[j][i] = count of element j produced by one decay of element i  (column = source).
  // Abundances a(t) evolve as a(t+1) = M·a(t), so long-run abundances ∝ dominant
  // right eigenvector of M and the growth factor is its Perron eigenvalue.
  const M = Array.from({ length: n }, () => new Float64Array(n));
  for (let i = 0; i < n; i++) {
    for (const k of decayOf.get(elements[i])) M[idx.get(k)][i] += 1;
  }
  let v = new Float64Array(n).fill(1);
  let lambda = 0;
  for (let it = 0; it < 40000; it++) {
    const w = new Float64Array(n);
    for (let r = 0; r < n; r++) { let s = 0; const Mr = M[r]; for (let c = 0; c < n; c++) s += Mr[c] * v[c]; w[r] = s; }
    let norm = 0; for (let r = 0; r < n; r++) norm += w[r] * w[r];
    norm = Math.sqrt(norm);
    if (norm === 0) break;
    for (let r = 0; r < n; r++) w[r] /= norm;
    lambda = norm;          // ||M v|| with v unit-norm → Perron eigenvalue
    v = w;
  }
  // normalize eigenvector to "atoms per million" (abundances)
  let sum = 0; for (let r = 0; r < n; r++) sum += v[r];
  const abundance = new Map();
  for (let r = 0; r < n; r++) abundance.set(elements[r], (v[r] / sum) * 1e6);
  return { lambda, abundance };
}

// ---------------------------------------------------------------------------
// ROAD 3 — the degree-71 polynomial (Conway). Coefficient list transcribed from
// MathWorld (Weisstein, "Conway's Constant"), highest degree first. λ is its unique
// real root > 1. We corroborate: evaluate at the empirically-found ratio and find the
// root by bisection, then compare.
// Polynomial (degree 71), from Conway 1987 / MathWorld:
// ---------------------------------------------------------------------------
// coefficients c[0]*x^71 + c[1]*x^70 + ... + c[71]
const POLY71 = [
  1, 0, -1, -2, -1, 2, 2, 1, -1, -1, -1, -1, -1, 2, 5, 3, -2, -10, -3, -2, 6, 6,
  1, 9, -3, -7, -8, -8, 10, 6, 8, -5, -12, 7, -7, 7, 1, -3, 10, 1, -6, -2, -10,
  -3, 2, 9, -3, 14, -8, 0, -7, 9, 3, -4, -10, -7, 12, 7, 2, -12, -4, -2, 5, 0, 1,
  -7, 7, -4, 12, -6, 3, -6
];
function polyEval(c, x) {
  let y = 0;
  for (let i = 0; i < c.length; i++) y = y * x + c[i];
  return y;
}
function rootNear(c, lo, hi) {
  let flo = polyEval(c, lo), fhi = polyEval(c, hi);
  if (flo === 0) return lo;
  if (fhi === 0) return hi;
  if (flo * fhi > 0) return NaN; // no sign change bracketed
  for (let i = 0; i < 200; i++) {
    const mid = (lo + hi) / 2, fm = polyEval(c, mid);
    if (fm === 0) return mid;
    if (flo * fm < 0) { hi = mid; fhi = fm; } else { lo = mid; flo = fm; }
  }
  return (lo + hi) / 2;
}

// ---------------------------------------------------------------------------
// RUN
// ---------------------------------------------------------------------------
console.log('CONWAY AUDIOACTIVE DECAY — verification\n' + '='.repeat(60));

// The canonical opening terms (A005150).
const KNOWN = ['1','11','21','1211','111221','312211','13112221','1113213211'];
let s = '1'; const gen = [s];
for (let i = 0; i < 7; i++) { s = lookAndSay(s); gen.push(s); }
check('opening terms match OEIS A005150', gen.join(',') === KNOWN.join(','),
      gen.slice(0, 8).join(' '));

// Only digits 1,2,3 ever appear in the standard sequence.
let big = '1'; for (let i = 0; i < 40; i++) big = lookAndSay(big);
check('standard sequence uses only digits 1,2,3', /^[123]+$/.test(big),
      'checked at term 40, length ' + big.length);
check('no run of length >3 in the standard sequence', !/(.)\1\1\1/.test(big),
      'no four equal adjacent digits');

// ROAD 1 — empirical ratio from several seeds (excluding the two fixed exceptions).
// Measure these seven seeds after 55 steps and check their distances from λ.
// This finite sample does not bound the error at every finite term.
// Roads 2 and 3 supply the more precise numerical approximations.
const seeds = ['1', '2', '3', '13', '1112', '3113322112', '111311222113111221131221'];
const ratios = seeds.map(sd => ({ sd, r: growthRatios(sd, 55).last }));
const rmin = Math.min(...ratios.map(x => x.r)), rmax = Math.max(...ratios.map(x => x.r));
const LAMBDA = 1.303577269034296391257099112152551890730702504659404;
check('seven measured seed ratios are within 0.002 of λ after 55 steps',
      Math.abs(rmin - LAMBDA) < 2e-3 && Math.abs(rmax - LAMBDA) < 2e-3,
      'ratios at term 55 in [' + rmin.toFixed(6) + ', ' + rmax.toFixed(6) + '] vs λ=' + LAMBDA.toFixed(6));

// The two exceptions are fixed: 22 has ratio 1; the empty ratio is undefined.
check('"22" is a fixed point (never grows)', lookAndSay('22') === '22', 'LAS(22)=' + lookAndSay('22'));
check('empty string is fixed', lookAndSay('') === '', 'LAS()=""');

// A previous size cap accepted these boundaries before the second-step collision.
const falseWallRight = '23' + '123'.repeat(5100);
check('a large boundary that collides on step two is rejected',
      !isWall('1', falseWallRight)
      && lookAndSay(lookAndSay('1' + falseWallRight)) !==
         lookAndSay(lookAndSay('1')) + lookAndSay(lookAndSay(falseWallRight)),
      'the old 30,000-character cap could incorrectly accept it');
check('certified splits and unresolved prefixes are distinguished',
      isWall('22', '12') && isWall('11132', '13211')
      && !isWall('1', '2'.repeat(1000)),
      'two known walls certified; an incomplete single-run prefix is left unsplit');

// ROAD 2 — derive the periodic table.
const { elements, decayOf } = derivePeriodicTable();
check('derived periodic table has exactly 92 common elements', elements.length === 92,
      'derived ' + elements.length + ' elements (Conway: 92)');

// Closure: every element decays only into elements of the table.
const set = new Set(elements);
let closed = true, maxLen = 0;
for (const e of elements) {
  maxLen = Math.max(maxLen, e.length);
  for (const k of decayOf.get(e)) if (!set.has(k)) closed = false;
}
check('the table is closed under decay', closed, 'no element decays outside the 92');
check('each derived decay concatenates to the actual next string',
      elements.every(e => decayOf.get(e).join('') === lookAndSay(e)),
      'all 92 decays preserve the look-and-say step');

// Hydrogen "22" is the unique non-decaying element (an atom that is its own derivative).
const nonDecaying = elements.filter(e => lookAndSay(e) === e);
check('exactly one element never decays (Hydrogen = "22")',
      nonDecaying.length === 1 && nonDecaying[0] === '22', nonDecaying.join(','));

// Perron eigenvalue of the 92×92 decay matrix = λ.
const { lambda: perron, abundance } = perronEigenpair(elements, decayOf);
check('Perron eigenvalue of the 92×92 decay matrix → λ',
      Math.abs(perron - LAMBDA) < 1e-6,
      'eigenvalue=' + perron.toFixed(9) + ' vs λ=' + LAMBDA.toFixed(9));

// Cross-check the derived abundances (Perron eigenvector) against Conway's published
// table (MathWorld). These strings and values are Conway's; matching them validates that
// our derived-from-scratch elements ARE his elements, abundances and all.
// Authoritative (name, string, abundance-per-million) triples from the Wikipedia /
// MathWorld periodic table of audioactive decay. Matching our derived abundances to
// these confirms our from-scratch elements ARE Conway's elements.
const NAMED = [
  ['Hydrogen', '22', 91790.383216],
  ['Calcium', '12', 56072.543129],
  ['Potassium', '1112', 43014.360913],
  ['Argon', '3112', 32997.170122],
  ['Copper', '131112', 18082.082203],
  ['Nickel', '11133112', 13871.123200],
  ['Protactinium', '13', 9883.5986392],
  ['Thorium', '1113', 7581.9047125],
  ['Actinium', '3113', 6926.9352045],
  ['Radium', '132113', 5313.7894999],
  ['Helium', '13112221133211322112211213322112', 3237.2968588],
  ['Uranium', '3', 102.56285249],
  ['Arsenic', '11131221131211322113322112', 27.246216076],
];
let abundOk = true, abundDetail = [];
for (const [name, str, want] of NAMED) {
  const got = abundance.get(str);
  const ok = got !== undefined && Math.abs(got - want) / want < 1e-4;
  if (!ok) abundOk = false;
  abundDetail.push(`${name}=${got === undefined ? 'MISSING' : got.toFixed(4)}(want ${want})`);
}
check('derived abundances match Conway’s published table (' + NAMED.length + ' named anchors, 91790→27/M)', abundOk,
      abundOk ? 'all match to 1 part in 10^4' : abundDetail.join('  '));

// Hydrogen is the most abundant; Arsenic the rarest of the 92.
const byAbund = [...abundance.entries()].sort((a, b) => b[1] - a[1]);
check('Hydrogen ("22") is the most abundant element', byAbund[0][0] === '22',
      'top=' + byAbund[0][0] + ' @ ' + byAbund[0][1].toFixed(1) + '/M');
check('Arsenic is the rarest of the 92', byAbund[byAbund.length - 1][0] === '11131221131211322113322112',
      'rarest @ ' + byAbund[byAbund.length - 1][1].toFixed(3) + '/M');

// ROAD 3 — degree-71 polynomial.
check('transcribed polynomial has degree 71', POLY71.length === 72,
      (POLY71.length - 1) + ' (coeffs: ' + POLY71.length + ')');
const polyRoot = rootNear(POLY71, 1.30, 1.31);
check('λ is a root of the degree-71 polynomial near 1.3036',
      Number.isFinite(polyRoot) && Math.abs(polyRoot - LAMBDA) < 1e-6,
      'root=' + (Number.isFinite(polyRoot) ? polyRoot.toFixed(9) : 'none bracketed') + ' vs λ=' + LAMBDA.toFixed(9));

// The transcribed polynomial equals OEIS A137275 (reversed) — an independent check that
// we did not mis-key Conway's polynomial.
const A137275_inc = [
  -6,3,-6,12,-4,7,-7,1,0,5,-2,-4,-12,2,7,12,-7,-10,-4,3,9,-7,0,-8,14,-3,9,2,-3,-10,
  -2,-6,1,10,-3,1,7,-7,7,-12,-5,8,6,10,-8,-8,-7,-3,9,1,6,6,-2,-3,-10,-2,3,5,2,-1,-1,
  -1,-1,-1,1,2,2,-1,-2,-1,0,1
];
check('our polynomial matches OEIS A137275 (Conway’s polynomial)',
      JSON.stringify(POLY71) === JSON.stringify([...A137275_inc].reverse()),
      'monic degree-71, coefficients identical to the OEIS record');

// ROAD 4: compare the matrix and polynomial approximations and measured ratios.
check('matrix eigenvalue and polynomial root agree to 12 decimal places',
      Number.isFinite(polyRoot) && perron.toFixed(12) === polyRoot.toFixed(12),
      'matrix=' + perron.toFixed(10) + '  poly=' + polyRoot.toFixed(10));
check('the seven measured ratios are within 0.002 of the matrix eigenvalue',
      Math.abs(rmax - perron) < 2e-3 && Math.abs(rmin - perron) < 2e-3,
      'empirical band [' + rmin.toFixed(5) + ',' + rmax.toFixed(5) + '] → ' + perron.toFixed(5));

// λ matches the published digits of OEIS A014715.
const polyRootHi = rootNear(POLY71, 1.303577, 1.303578);
check('λ matches OEIS A014715 to 12 digits',
      Math.abs(polyRootHi - LAMBDA) < 5e-13,
      'root=' + polyRootHi.toFixed(15));

// ---------------------------------------------------------------------------
console.log('');
for (const [st, name, detail] of results) {
  console.log(`  ${st === 'PASS' ? '✓' : '✗'} ${name}${detail ? '  — ' + detail : ''}`);
}
console.log('\n' + '='.repeat(60));
console.log(`${PASS}/${PASS + FAIL} checks passed.` + (FAIL ? `  ${FAIL} FAILED.` : ''));

// Emit a JSON artifact of the derived periodic table for the page to load.
if (!FAIL) {
  // atomic numbers for the elements we can confidently name (by string)
  const NUM = { '22':1, '12':20, '1112':19, '3112':18, '131112':29, '11133112':28,
    '13':91, '1113':90, '3113':89, '132113':88,
    '13112221133211322112211213322112':2, '3':92, '11131221131211322113322112':33,
    '312211322212221121123222112':3 };
  const nameFull = { 1:'Hydrogen',2:'Helium',3:'Lithium',18:'Argon',19:'Potassium',
    20:'Calcium',28:'Nickel',29:'Copper',33:'Arsenic',88:'Radium',89:'Actinium',
    90:'Thorium',91:'Protactinium',92:'Uranium' };
  const nameByStr = new Map(Object.entries(NUM).map(([s, num]) => [s, nameFull[num]]));
  const table = [...abundance.entries()]
    .sort((a, b) => b[1] - a[1])
    .map(([str, ab]) => ({
      string: str,
      length: str.length,
      abundance: Number(ab.toFixed(6)),
      decaysInto: decayOf.get(str),
      name: nameByStr.get(str) || null,
      number: NUM[str] || null,
    }));
  const artifact = {
    lambda: polyRootHi,
    lambdaDigits: '1.303577269034296391257099112152551890730702504659404',
    elementCount: elements.length,
    longestElementLength: maxLen,
    poly71_highFirst: POLY71,
    table,
    generatedBy: 'research/conway-audioactive/verify.mjs',
  };
  const fs = await import('node:fs');
  const url = await import('node:url');
  const dir = url.fileURLToPath(new URL('.', import.meta.url));
  fs.writeFileSync(dir + 'table.json', JSON.stringify(artifact, null, 0));
  console.log('\nDerived facts:');
  console.log('  elements:', elements.length, ' longest length:', maxLen);
  console.log('  λ (matrix Perron): ', perron.toFixed(12));
  console.log('  λ (poly-71 root):  ', polyRootHi.toFixed(15));
  console.log('  wrote table.json (' + table.length + ' elements w/ abundances + decay)');
}
process.exit(FAIL ? 1 : 0);
