#!/usr/bin/env node
// Verifier for "The Crystal and the Cloud" — Stanley sequences (Odlyzko–Stanley 1978).
// Checks finite samples of the stratum's numeric/structural claims. No network; pure greedy.
//
// What is checked here, and what is NOT (the honesty spine):
//  - Finite checks of known results: 32 S(0,1) terms against A005836; 64 against
//    the binary-read-as-ternary formula and 3-freeness. Other seeds are checked
//    for 3-freeness on 200 terms. Sampled counts are compared with Moy's bound.
//    These finite computations do not prove the infinite results.
//  - CONJECTURAL facts we only *illustrate* (and label as such): the Type-1/Type-2
//    dichotomy, and the Type-2 growth Θ(n²/log n). Empirical slopes are measurements,
//    not proofs. No Stanley sequence has been PROVEN irregular; we never claim one is.

let pass = 0, fail = 0;
const eq = (name, got, want) => {
  const ok = JSON.stringify(got) === JSON.stringify(want);
  console.log(`${ok ? 'ok  ' : 'FAIL'}  ${name}`);
  if (ok) pass++; else { fail++; console.log(`      got : ${JSON.stringify(got)}`); console.log(`      want: ${JSON.stringify(want)}`); }
};
const ok = (name, cond, detail='') => { console.log(`${cond?'ok  ':'FAIL'}  ${name}${detail?'  ('+detail+')':''}`); cond?pass++:fail++; };

// --- the greedy machine: lexicographically-least 3-free extension ----------------
// 3-term AP a<b<c means a + c = 2b. Adding candidate c is forbidden iff there exist
// earlier terms a<b with a + c = 2b, i.e. some b with (2b - c) already present and < c.
function stanley(seed, N) {
  const s = seed.slice();
  const have = new Set(s);
  let next = s[s.length - 1] + 1;
  while (s.length < N) {
    let c = next, good = false;
    for (;;) {
      good = true;
      for (const b of s) {
        const a = 2 * b - c;
        if (a >= 0 && a < c && have.has(a)) { good = false; break; }
      }
      if (good) break;
      c++;
    }
    s.push(c); have.add(c); next = c + 1;
  }
  return s;
}

// brute-force 3-free check (independent of the construction logic)
function isThreeFree(arr) {
  const set = new Set(arr);
  for (let i = 0; i < arr.length; i++)
    for (let j = i + 1; j < arr.length; j++) {
      const c = 2 * arr[j] - arr[i];      // arr[i] < arr[j] < c
      if (c > arr[j] && set.has(c)) return false;
    }
  return true;
}

// ============================ 1. S(0,1) == A005836 ============================
const S01 = stanley([0, 1], 64);
// OEIS A005836 first terms (numbers whose base-3 representation contains no 2):
const A005836 = [0,1,3,4,9,10,12,13,27,28,30,31,36,37,39,40,81,82,84,85,90,91,93,94,
                 108,109,111,112,117,118,120,121];
eq('S(0,1) first 32 terms == OEIS A005836', S01.slice(0, 32), A005836);

// closed form: a_n = value of (binary expansion of n) read in base 3
const b2asb3 = n => parseInt(n.toString(2), 3);
ok('S(0,1): a_n = binary(n) read in base 3, for all n < 64',
   S01.every((v, n) => v === b2asb3(n)));

// Finite digit check on the 64 computed S(0,1) terms.
const noDigit2 = m => !m.toString(3).includes('2');
ok('S(0,1): first 64 terms have no digit 2 in base 3',
   S01.every(noDigit2));

ok('S(0,1) is genuinely 3-free (independent brute check, 64 terms)', isThreeFree(S01));

// ====================== 2. greedy == 3-free for every seed ======================
const SEEDS = [[0,1],[0,2],[0,4],[0,5],[0,15],[0,3,4],[1,2]];
let allFree = true;
for (const seed of SEEDS) if (!isThreeFree(stanley(seed, 200))) allFree = false;
ok('every featured Stanley sequence is 3-free (200 terms each, brute-checked)', allFree);

// =================== 3. growth exponents (empirical, labelled) ==================
// Fit log a_n = p·log n + c by least squares over a tail window. These are MEASUREMENTS
// that illustrate the conjectured dichotomy; they are not proofs of any growth law.
function slope(seq, lo, hi) {       // seq[n] = a_n; fit over n in [lo,hi)
  let sx=0,sy=0,sxx=0,sxy=0,k=0;
  for (let n = lo; n < hi; n++) {
    if (seq[n] <= 0) continue;
    const x = Math.log(n), y = Math.log(seq[n]);
    sx+=x; sy+=y; sxx+=x*x; sxy+=x*y; k++;
  }
  return (k*sxy - sx*sy) / (k*sxx - sx*sx);
}
const N = 4000;
const data = Object.fromEntries(SEEDS.map(s => [JSON.stringify(s), stanley(s, N)]));
const log2_3 = Math.log(3) / Math.log(2);
ok('log2(3) = 1.58496… (the Type-1 exponent)', Math.abs(log2_3 - 1.5849625007211562) < 1e-12,
   log2_3.toFixed(10));

const sl01 = slope(data['[0,1]'], 200, N);
ok('S(0,1) empirical log-log slope over [200,4000) is within 0.06 of log2(3)', Math.abs(sl01 - log2_3) < 0.06,
   `slope=${sl01.toFixed(4)} vs ${log2_3.toFixed(4)}`);

// The cloud candidates have steeper finite-window fits. We assert ONLY that they are
// steeper than the crystal — never that they equal any conjectured rate.
for (const seed of [[0,4],[0,5],[0,15]]) {
  const s = slope(data[JSON.stringify(seed)], 400, N);
  ok(`S(${seed.join(',')}) empirical slope is steeper than the crystal's`,
     s > sl01 + 0.08, `slope=${s.toFixed(4)}`);
}

// ===================== 4. Moy (2011) general lower bound ========================
// Moy proved the counting function S(A,x) ≥ (√2 − ε)√x for large x (resolving a question
// of Erdős–Sárközy–Sós–et al.). Thus, for every ε > 0, a_n ≤ (1/2+ε)n²
// eventually. Below we only sample counts in two 4000-term prefixes, requiring
// at least 0.9·√2·√x for the sampled x > 200. This is not a proof of the bound.
function countingOK(seq) {
  const X = seq[seq.length - 1];
  for (let x = 50; x <= X; x += Math.max(1, (X/200)|0)) {
    let cnt = 0; for (const v of seq) if (v <= x) cnt++;
    // Finite sampling criterion, with x > 200 chosen for this check.
    if (x > 200 && cnt < 0.9 * Math.SQRT2 * Math.sqrt(x)) return false;
  }
  return true;
}
ok('S(0,4): sampled counts for x>200 are ≥ 0.9·√2·√x (4000-term prefix)',
   countingOK(data['[0,4]']));
ok('S(0,15): sampled counts for x>200 are ≥ 0.9·√2·√x (4000-term prefix)',
   countingOK(data['[0,15]']));

// Finite term comparison on S(0,4); not a universal finite-n consequence of Moy.
ok('S(0,4): a_n < n²/2 for 10 ≤ n < 4000 (finite comparison)',
   data['[0,4]'].every((v,n) => n < 10 || v < n*n/2));

// ----------------------------------------------------------------------------------
console.log(`\n${pass}/${pass+fail} checks passed`);

// Emit finite figures with their actual sample sizes and fit windows.
const figures = {
  log2_3,
  S01_first16: S01.slice(0,16),
  closedFormHolds: S01.every((v, n) => v === b2asb3(n)),
  closedFormTerms: S01.length,
  oeisTerms: A005836.length,
  slope_S01: +sl01.toFixed(4),
  slope_S04: +slope(data['[0,4]'],400,N).toFixed(4),
  slope_S05: +slope(data['[0,5]'],400,N).toFixed(4),
  slope_S15: +slope(data['[0,15]'],400,N).toFixed(4),
  windows: { crystal: `n ∈ [200, ${N})`, clouds: `n ∈ [400, ${N})` },
};
console.log('\nFIGURES ' + JSON.stringify(figures));
process.exit(fail ? 1 : 0);
