// research/how-magnets-work/verify.mjs
// Offline verifier for the stratum "How Do Magnets Work?" (/strata/how-magnets-work/).
// Three independent checks, each a number the page shows the reader:
//   (1) The 2D Ising critical temperature is Onsager's EXACT 2/ln(1+√2) — the page's
//       live spin grid orders below it and disorders above it.
//   (2) Magnetic DIPOLE–dipole coupling at iron's lattice spacing is ~10^4 times too
//       weak (in temperature units) to explain iron's 1043 K Curie point — so the thing
//       that holds a magnet together is NOT a magnetic force. It is the (electrostatic,
//       quantum) exchange interaction.
//   (3) Purcell's relativity identity: the LAB-frame MAGNETIC force on a charge moving
//       past a neutral current-carrying wire equals the CHARGE-frame ELECTRIC force that
//       appears purely from relativistic length contraction — agreement to machine
//       precision, hinging on μ0·ε0 = 1/c². A current's magnetic force is the relativistic
//       shadow of electricity.
// Run: node research/how-magnets-work/verify.mjs   (no deps; exact where exact is possible)

let pass = 0, fail = 0;
const approx = (a, b, rel, msg) => {
  const ok = Math.abs(a - b) <= rel * Math.max(Math.abs(a), Math.abs(b), 1e-300);
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${msg}`);
  if (!ok) console.log(`        got ${a}  expected ${b}  (rel tol ${rel})`);
  ok ? pass++ : fail++;
};
const eq = (cond, msg) => { console.log(`${cond ? 'PASS' : 'FAIL'}  ${msg}`); cond ? pass++ : fail++; };

console.log('\n=== (1) Onsager: the exact 2D Ising critical temperature ===');
// Onsager (1944): sinh(2J/kT_c) = 1  →  kT_c/J = 2/ln(1+√2).
const Tc = 2 / Math.log(1 + Math.SQRT2);
console.log(`  kT_c/J = 2/ln(1+√2) = ${Tc.toFixed(6)}`);
approx(Tc, 2.269185, 1e-5, 'kT_c/J = 2.269185… (Onsager 1944, exact)');
// The defining condition, checked directly: sinh(2/Tc) must equal 1.
approx(Math.sinh(2 / Tc), 1, 1e-12, 'sinh(2J/kT_c) = 1 at that temperature');

console.log('\n=== (2) A magnetic dipole is far too weak to make a magnet ===');
// Physical constants (CODATA 2018).
const mu0  = 1.25663706212e-6;   // T·m/A  (vacuum permeability)
const muB  = 9.2740100783e-24;   // J/T    (Bohr magneton)
const kB   = 1.380649e-23;       // J/K    (Boltzmann, exact by SI def)
const eV   = 1.602176634e-19;    // J      (electronvolt, exact)
// Iron: BCC, lattice constant a = 0.28665 nm; nearest neighbours along the body
// diagonal at r = (√3/2)·a. Moment per atom m = 2.22 μ_B (Kittel, Solid State Physics).
const a_Fe = 0.28665e-9;
const r_nn = (Math.sqrt(3) / 2) * a_Fe;
const m_Fe = 2.22 * muB;
console.log(`  Fe nearest-neighbour distance r = ${(r_nn * 1e9).toFixed(4)} nm`);
// Order-of-magnitude dipolar coupling energy: U ≈ (μ0/4π)·m²/r³.
const U_dip = (mu0 / (4 * Math.PI)) * (m_Fe * m_Fe) / Math.pow(r_nn, 3);
const T_dip = U_dip / kB;            // the temperature that energy corresponds to
console.log(`  U_dipole ≈ ${U_dip.toExponential(3)} J  =  ${(U_dip / eV).toExponential(3)} eV  →  ${T_dip.toFixed(3)} K`);
eq(T_dip < 1, 'dipolar coupling, as a temperature, is below 1 K (≪ a magnet)');
// Iron's measured Curie temperature.
const Tc_Fe = 1043;                  // K (Kittel, Table; 770 °C)
const ratio = Tc_Fe / T_dip;
console.log(`  Fe Curie temperature = ${Tc_Fe} K  →  ratio T_Curie / T_dipole ≈ ${Math.round(ratio).toLocaleString('en-US')}×`);
eq(ratio > 1000, 'iron orders at ~1000–10000× the dipolar scale → dipoles can\'t do it');
// The energy that DOES order iron is the exchange J, of order kB·T_Curie — an
// electron-volt-scale, electrostatic energy (Coulomb + Pauli), not a magnetic one.
const J_exch = kB * Tc_Fe;
console.log(`  exchange scale  J ≈ kB·T_Curie = ${(J_exch / eV).toExponential(3)} eV  (electrostatic, ~10^4× the dipolar energy)`);
approx(J_exch / U_dip, ratio, 1e-9, 'exchange/dipolar energy ratio = the Curie/dipole temperature ratio');

console.log('\n=== (3) Purcell: a current\'s magnetic force IS electricity, seen from a moving frame ===');
// Model (Purcell & Morin, Electricity and Magnetism, 3e, §5.9): an infinite straight
// wire, neutral in the lab. A line of + ions at rest (lab linear density +λ0) and a
// line of electrons drifting at velocity v (lab linear density −λ0, so the wire is
// neutral and carries current I = λ0·v). A test charge q moves parallel at velocity u.
const c   = 299792458;               // m/s (exact)
const eps0 = 1 / (mu0 * c * c);       // F/m  — the identity μ0·ε0 = 1/c²
const eps0_codata = 8.8541878128e-12; // F/m  (vacuum permittivity, CODATA 2018), checked against it below
const lam0 = 1.0e-6;                  // C/m  (an arbitrary positive linear density)
const q    = 1.0e-9;                  // C
const r    = 0.02;                    // m   (test charge's distance from the wire)
// Use frankly relativistic speeds so the agreement is a real test, not round-off:
const v = 0.40 * c;                   // electron drift (idealised)
const u = 0.30 * c;                   // test-charge speed
const gamma = (s) => 1 / Math.sqrt(1 - (s * s) / (c * c));

// --- LAB FRAME: wire neutral, current I = λ0 v, magnetic force on the moving charge.
const I = lam0 * v;
const B = mu0 * I / (2 * Math.PI * r);
const F_mag_lab = q * u * B;          // F = q u B (magnitude)
console.log(`  LAB:    I = ${I.toExponential(3)} A,  B = ${B.toExponential(3)} T,  F_magnetic = ${F_mag_lab.toExponential(6)} N`);

// --- CHARGE'S FRAME (boost by u): the wire is no longer neutral. Each line's linear
// density in a frame = γ(its speed in that frame) × (its REST linear density). The
// ions are at rest in the lab so their rest density is +λ0; the electrons move at v in
// the lab, so their rest density is −λ0/γ(v).
const lam_ion_rest = +lam0;
const lam_ele_rest = -lam0 / gamma(v);
// Velocities in the charge's frame (relativistic velocity addition, boost +u):
const addVel = (w) => (w - u) / (1 - (w * u) / (c * c));
const v_ion_p = addVel(0);            // = −u
const v_ele_p = addVel(v);
// Linear densities in the charge's frame:
const lam_ion_p = gamma(v_ion_p) * lam_ion_rest;
const lam_ele_p = gamma(v_ele_p) * lam_ele_rest;
const lam_net_p = lam_ion_p + lam_ele_p;   // net charge per length the charge "sees"
console.log(`  CHARGE FRAME: net linear density λ' = ${lam_net_p.toExponential(6)} C/m  (wire looks charged!)`);
const E_p = lam_net_p / (2 * Math.PI * eps0 * r);
const F_elec_p = q * E_p;             // purely electric force in the charge's frame
// A transverse force on a charge AT REST in the primed frame, transformed back to the
// lab, divides by γ(u):  F_lab = F'/γ(u).
const F_elec_lab = F_elec_p / gamma(u);
console.log(`  CHARGE FRAME: F_electric' = ${F_elec_p.toExponential(6)} N  →  back in lab: ${F_elec_lab.toExponential(6)} N`);
approx(F_elec_lab, F_mag_lab, 1e-12, 'magnetic force (lab) = electric force (charge frame), to machine precision');
// And the hinge that makes it work:
// Taken with CODATA's own ε0, not the ε0 derived above, so this check can fail
// (CODATA 2018 gives μ0 and ε0 each to a relative uncertainty of 1.5e-10).
approx(mu0 * eps0_codata, 1 / (c * c), 1e-9, 'μ0·ε0 = 1/c², with CODATA 2018 μ0 and ε0  (the identity that fuses E and B)');

console.log(`\n${fail === 0 ? '✓ ALL CHECKS PASS' : '✗ ' + fail + ' FAILED'}  (${pass} passed, ${fail} failed)\n`);
process.exit(fail === 0 ? 0 : 1);
