#!/usr/bin/env node
// verify.mjs — EXACT + reproducible checks for "Entropy is not disorder" (Neat Has Nothing to Do With It).
// Run: node verify.mjs        (assertions)
//      node verify.mjs --json  (also (re)write page.json for the immersive page)
// No external data. Combinatorics are exact (BigInt); the entropic-ordering signal is a
// reproducible hard-disk Monte-Carlo measurement (see harddisk.mjs).
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { writeFileSync } from 'node:fs';
import { run as mcRun } from './harddisk.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const kB = 1.380649e-23;            // J/K, exact SI-defining constant since 2019
const R  = 8.314462618;            // J/mol/K
let pass=0, fail=0; const log=[];
function ok(name, cond, got){ (cond?pass++:fail++); log.push({name, ok:!!cond, got:String(got)}); if(!cond) console.error('FAIL:', name,'=>',got); }
const binom=(n,k)=>{ if(k<0||k>n) return 0n; k=Math.min(k,n-k); let num=1n,den=1n; for(let i=0;i<k;i++){num*=BigInt(n-i);den*=BigInt(i+1);} return num/den; };
const lnBig=x=>{ if(x<=0n) return -Infinity; const s=x.toString(),dg=s.length; return Math.log(Number(s.slice(0,15)))+(dg-Math.min(15,dg))*Math.log(10); };

// ---- 1. Two-chamber gas: macrostate n_left of N; microstates = C(N,n); S=kB ln C ----
const N=100;
ok('all-on-one-side is exactly ONE microstate (S=0)', binom(N,0)===1n, binom(N,0));
let argmax=0,mw=0n; for(let n=0;n<=N;n++){const w=binom(N,n); if(w>mw){mw=w;argmax=n;}}
ok('microstates peak at the even split', argmax===N/2, `argmax=${argmax}`);
ok('C(100,50) exact', binom(100,50)===100891344545564193334812497256n, binom(100,50));
const pAll = 1/2**N;
ok('P(all 100 on one side) < 1e-30', pAll<1e-30, pAll.toExponential(2));
const Scurve = Array.from({length:N+1},(_,n)=>+(lnBig(binom(N,n))).toFixed(4)); // S/kB vs n
ok('S/kB(even)=ln C(100,50) ~ 66.78', Math.abs(Scurve[50]-66.784)<0.01, Scurve[50]);

// ---- 2. Einstein solid: q quanta among Nosc oscillators; W=C(q+Nosc-1,Nosc-1) ----
const Nosc=50;
ok('adding energy raises microstates', binom(20+Nosc-1,Nosc-1)>binom(10+Nosc-1,Nosc-1), 'W(20)>W(10)');
ok('W(q=1)=Nosc', binom(1+Nosc-1,Nosc-1)===BigInt(Nosc), binom(Nosc,Nosc-1));

// ---- 3. Entropy of mixing & Gibbs paradox ----
const dS_binary_perTotalMole = -(0.5*Math.log(0.5)*2);             // = ln2  (per total mole)
ok('mixing equal binary: ΔS = R ln2 per total mole', Math.abs(dS_binary_perTotalMole-Math.log(2))<1e-12, dS_binary_perTotalMole.toFixed(6));
const oneMoleEach = 2*R*Math.log(2);                                // n=2 total moles
ok('one mole of each: ΔS = 2R ln2 ≈ 11.53 J/K', Math.abs(oneMoleEach-11.526)<0.01, oneMoleEach.toFixed(3));
ok('Gibbs: identical gases ΔS=0 (needs indistinguishable N! counting)', true, 'by construction');

// ---- 4. Entropic ordering: hard-disk MC melts order at low density, keeps it at high ----
// energy is identically zero in every valid config => any ordering is entropy alone.
const dens=[0.45,0.55,0.65,0.70,0.72,0.74];
const seeds=[7,99,2024];
const curve=dens.map(eta=>{
  const vals=seeds.map(seed=>mcRun(eta,{nx:14,ny:14,sweeps:2200,seed}).psi6);
  const m=vals.reduce((a,b)=>a+b,0)/vals.length;
  const sd=Math.sqrt(vals.reduce((a,b)=>a+(b-m)**2,0)/vals.length);
  return {eta, psi6:+m.toFixed(3), sd:+sd.toFixed(3)};
});
const lo=curve.find(c=>c.eta===0.45).psi6, hi=curve.find(c=>c.eta===0.74).psi6, mid=curve.find(c=>c.eta===0.70).psi6;
ok('ordered lattice MELTS at low density (psi6<0.5 at eta=0.45)', lo<0.5, lo);
ok('order PERSISTS/sharpens at high density (psi6>0.8 at eta=0.74)', hi>0.8, hi);
ok('sharp rise through the 2D transition region ~0.70 (psi6>0.7)', mid>0.7, mid);
ok('psi6 rises monotonically with density', curve.every((c,i)=>i===0||c.psi6>=curve[i-1].psi6-0.02), curve.map(c=>c.psi6).join(','));
ok('signal is seed-robust (all sd<0.05)', curve.every(c=>c.sd<0.05), Math.max(...curve.map(c=>c.sd)).toFixed(3));

console.log(`\n${pass} passed, ${fail} failed`);
if(process.argv.includes('--verify-only')) process.exit(fail?1:0);

// ---- page.json: everything the immersive page renders, checked here ----
const page = {
  generatedBy: 'research/entropy-not-disorder/verify.mjs',
  constants: { kB, R, kB_units:'J/K', note:'kB exact (SI-defining since 2019)' },
  twoChamber: { N, C_100_50: binom(100,50).toString(), S_over_kB_even:+Scurve[50].toFixed(3),
                P_all_one_side: pAll, S_curve_over_kB: Scurve },
  mixing: { equalBinary_perTotalMole_over_R: +Math.log(2).toFixed(5), oneMoleEach_JperK: +oneMoleEach.toFixed(3) },
  hardDisk: { orderParam:'<|psi6|> (per-particle bond-orientational order; 1=perfect triangular)',
              seeds, sweeps:2200, N:196, curve },
  facts: {
    boltzmann: 'S = k·log W (natural log); W = number of microstates consistent with the macrostate. Engraved "S = k. log W" on Boltzmann\'s memorial grave, Vienna Zentralfriedhof (honorary grave 1929; the monument bearing the formula unveiled 4 July 1933).',
    planck: 'Boltzmann established S ∝ log(probability) in 1877; Planck first wrote the equation in this compact form and introduced the constant k (1900–1901), naming it the Boltzmann constant.',
    hardSphere3D: 'Hard spheres freeze by entropy alone: coexistence η_freeze≈0.494, η_melt≈0.545 (Hoover & Ree 1968). Discovered by Alder & Wainwright (MD) and Wood & Jacobson (MC), both J. Chem. Phys. 27 (1957); conjectured by Kirkwood (late 1930s–1951).',
    packing: 'FCC close packing = π/(3√2) ≈ 0.7405 (Kepler/Hales max). Random close packing ≈ 0.64 is NOT rigorously well-defined (Torquato, Truskett & Debenedetti, PRL 84, 2000).',
    hardDisk2D: '2D melting is two-step: liquid→hexatic→solid. Liquid–hexatic is first-order, coexistence onset ~η=0.70 (Bernard & Krauth, PRL 107, 2011); the sim here is illustrative of the mechanism.',
    onsager: 'Long hard rods align into a nematic by entropy alone (Onsager, Ann. N.Y. Acad. Sci. 51, 627, 1949).',
    hydrophobic: 'Oil and water separating can RAISE total entropy: structured water caging nonpolar solute is low-entropy; demixing frees it (entropy-dominated near room T; enthalpy grows at higher T). Kauzmann 1959; Chandler, Nature 437, 640 (2005).',
    rubber: 'Rubber elasticity is entropic: stretching lowers chain conformational entropy; restoring force ∝ T (Gough–Joule: a stretched band contracts when heated). Treloar.',
    dispute: 'The replacement for "disorder" is itself unsettled: "energy dispersal" (Lambert, J.Chem.Educ. 79, 187 & 1241, 2002; changed US textbooks) vs "missing information / microstate count" (Ben-Naim, J.Chem.Educ. 88, 594, 2011). Styer (Am.J.Phys. 68, 1090, 2000) calls BOTH "disorder" and "freedom" flawed similes.',
    fair: 'The metaphor sometimes works: melting ice is both an entropy increase and an obvious loss of order. It just is not reliable.'
  }
};
if(process.argv.includes('--json')){ writeFileSync(join(HERE,'page.json'), JSON.stringify(page,null,2)); console.log('wrote page.json'); }
