import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';

const here = fileURLToPath(new URL('.', import.meta.url));
const htmlPath = fileURLToPath(new URL('../../public/strata/stern-gerlach/index.html', import.meta.url));
const mdPath = fileURLToPath(new URL('../../src/content/strata/stern-gerlach.md', import.meta.url));
const html = readFileSync(htmlPath, 'utf8');
const markdown = readFileSync(mdPath, 'utf8');

let checks = 0;
function check(condition, message) {
  checks += 1;
  assert.ok(condition, message);
}
function close(actual, expected, tolerance, message) {
  checks += 1;
  assert.ok(Math.abs(actual - expected) <= tolerance,
    `${message}: got ${actual}, expected ${expected} within ${tolerance}`);
}
function relativeClose(actual, expected, tolerance, message) {
  checks += 1;
  const relative = Math.abs(actual - expected) / Math.abs(expected);
  assert.ok(relative <= tolerance,
    `${message}: got ${actual}, expected ${expected}, relative error ${relative}`);
}

const source = Object.freeze({
  elementaryCharge: 1.602176634e-19,
  planck: 6.62607015e-34,
  electronMass: 9.1093837139e-31,
  bohrMagneton: 9.2740100657e-24,
  atomicMass: 1.66053906892e-27,
  silverU: 107.8682
});

const hbar = source.planck / (2 * Math.PI);
const derivedBohrMagneton =
  source.elementaryCharge * hbar / (2 * source.electronMass);
relativeClose(derivedBohrMagneton, source.bohrMagneton, 5e-11,
  'external anchor, 2022 CODATA Bohr magneton from e*hbar/(2*me)');

function enumerate(j) {
  const twiceJ = Math.round(2 * j);
  const out = [];
  for (let twiceM = -twiceJ; twiceM <= twiceJ; twiceM += 2) {
    out.push(twiceM === 0 ? 0 : twiceM / 2);
  }
  return out;
}

function projectionSet(kind) {
  if (kind === 'old') {
    return enumerate(1).filter((m) => m !== 0).map((m) => m);
  }
  if (kind === 'orbital') return enumerate(0).map((m) => m);
  if (kind === 'spin') return enumerate(0.5).map((m) => 2 * m);
  if (kind === 'l1') return enumerate(1).map((m) => m);
  throw new Error(`unknown model ${kind}`);
}

assert.deepEqual(enumerate(0.5), [-0.5, 0.5]);
checks += 1;
assert.deepEqual(enumerate(1), [-1, 0, 1]);
checks += 1;
assert.deepEqual(projectionSet('old'), [-1, 1]);
checks += 1;
assert.deepEqual(projectionSet('orbital'), [0]);
checks += 1;
assert.deepEqual(projectionSet('spin'), [-1, 1]);
checks += 1;
assert.deepEqual(projectionSet('l1'), [-1, 0, 1]);
checks += 1;

function exactIntegral(a) {
  return a.gradient * (
    a.length * a.drift +
    a.length * a.length / 2 -
    a.tilt * a.length * a.length / 6
  );
}

function midpointIntegral(a, steps = 20001) {
  let sum = 0;
  const dx = a.length / steps;
  for (let i = 0; i < steps; i += 1) {
    const x = (i + 0.5) * dx;
    const gradient = a.gradient *
      (1 + a.tilt * (2 * x / a.length - 1));
    sum += (a.length + a.drift - x) * gradient;
  }
  return sum * dx;
}

function kMm(a, speed = a.speed) {
  const silverMass = source.silverU * source.atomicMass;
  return 1000 * source.bohrMagneton * exactIntegral(a) /
    (silverMass * speed * speed);
}

const defaults = Object.freeze({
  gradient: 1000,
  tilt: 0,
  speed: 500,
  length: 0.035,
  drift: 0.2,
  slit: 0.05,
  thermal: 0.08,
  resolution: 0.04
});

const defaultIntegral = exactIntegral(defaults);
const defaultK = kMm(defaults);
const silverMass = source.silverU * source.atomicMass;
close(defaultIntegral, 7.6125, 1e-13, 'default lever integral in T*m');
close(defaultK, 1.576566630649403, 1e-12,
  'default detector shift in mm per Bohr magneton');
close(silverMass, 1.7911936039407634e-25, 1e-39,
  'natural-silver mass proxy in kg');

function gaussian(x, mean, sigma) {
  const z = (x - mean) / sigma;
  return Math.exp(-0.5 * z * z) /
    (Math.sqrt(2 * Math.PI) * sigma);
}

function independentErf(x) {
  if (x === 0) return 0;
  const sign = x < 0 ? -1 : 1;
  const z = Math.abs(x);
  const t = 1 / (1 + 0.5 * z);
  const tail = t * Math.exp(
    -z * z - 1.26551223 +
    t * (1.00002368 +
    t * (0.37409196 +
    t * (0.09678418 +
    t * (-0.18628806 +
    t * (0.27886807 +
    t * (-1.13520398 +
    t * (1.48851587 +
    t * (-0.82215223 +
    t * 0.17087277))))))))
  );
  return sign * (1 - tail);
}

function normalCdf(z) {
  return 0.5 * (1 + independentErf(z / Math.SQRT2));
}

function detectorKernel(delta, slitWidth, resolution) {
  if (slitWidth < 1e-12) return gaussian(delta, 0, resolution);
  return (
    normalCdf((delta + slitWidth / 2) / resolution) -
    normalCdf((delta - slitWidth / 2) / resolution)
  ) / slitWidth;
}

function velocityNodes(a) {
  if (a.thermal === 0) return [{ v: a.speed, w: 1 }];
  const nodes = [];
  let total = 0;
  for (let i = 0; i < 41; i += 1) {
    const z = -3 + 6 * i / 40;
    const weight = Math.exp(-0.5 * z * z);
    nodes.push({
      v: a.speed * (1 + a.thermal * z),
      w: weight
    });
    total += weight;
  }
  return nodes.map((node) => ({ v: node.v, w: node.w / total }));
}

function density(kind, x, a) {
  const velocities = velocityNodes(a);
  const qs = kind === 'classical'
    ? Array.from({ length: 121 }, (_, i) => -1 + (i + 0.5) * 2 / 121)
    : projectionSet(kind);
  let total = 0;
  for (const q of qs) {
    for (const node of velocities) {
      total += detectorKernel(
        x - q * kMm(a, node.v), a.slit, a.resolution
      ) *
        node.w / qs.length;
    }
  }
  return total;
}

function integrateDensity(kind, a, halfWindow = 8, step = 0.02) {
  let sum = 0;
  let previous = density(kind, -halfWindow, a);
  for (let x = -halfWindow + step;
    x <= halfWindow + 1e-9; x += step) {
    const current = density(kind, x, a);
    sum += 0.5 * (previous + current) * step;
    previous = current;
  }
  return sum;
}

const centers = {};
for (const kind of ['classical', 'old', 'orbital', 'spin', 'l1']) {
  centers[kind] = density(kind, 0, defaults);
}
close(centers.classical, 0.319130712003525, 5e-7,
  'initial classical central density');
check(centers.classical > 0.3,
  'classical continuum must retain substantial density at the center');
check(centers.old < 1e-100,
  'old two-component rule must have a central minimum at default blur');
close(centers.old, centers.spin, Number.MIN_VALUE,
  'old rule and ideal g=2 spin density must coincide');
close(centers.orbital, 9.360581080950912, 5e-5,
  'initial orbital-only central density');
check(centers.orbital > centers.classical * 20,
  'orbital-only ground-state silver must remain centered');
close(centers.l1, 3.120193693650304, 5e-5,
  'initial modern L=1 central density');
check(centers.l1 > 3,
  'modern L=1 must retain its m=0 central component');

for (const kind of ['classical', 'old', 'orbital', 'spin', 'l1']) {
  close(integrateDensity(kind, defaults), 1, 5e-7,
    `${kind} probability captured by the initial fixed window`);
}

const oldPositions = projectionSet('old').map((q) => q * defaultK);
const spinPositions = projectionSet('spin').map((q) => q * defaultK);
assert.deepEqual(oldPositions, spinPositions);
checks += 1;
close(Math.max(
  Math.abs(oldPositions[0] - spinPositions[0]),
  Math.abs(oldPositions[1] - spinPositions[1])
), 0, 0, 'old-rule versus ideal-spin position residual');

let randomState = 0x19220208;
function random() {
  randomState = (1664525 * randomState + 1013904223) >>> 0;
  return randomState / 4294967296;
}

for (let trial = 0; trial < 24; trial += 1) {
  const a = {
    gradient: 100 + 1500 * random(),
    tilt: -0.6 + 1.2 * random(),
    speed: 250 + 650 * random(),
    length: 0.01 + 0.05 * random(),
    drift: 0.04 + 0.31 * random(),
    slit: 0.01 + 1.49 * random(),
    thermal: 0.25 * random(),
    resolution: 0.01 + 1.49 * random()
  };
  const exact = exactIntegral(a);
  const numeric = midpointIntegral(a);
  check(exact > 0, `trial ${trial} must have a nonzero positive lever integral`);
  relativeClose(numeric, exact, 2e-10,
    `trial ${trial} independent midpoint integral`);
  check(kMm(a) > 0, `trial ${trial} must retain a nonzero apparatus response`);
  const old = projectionSet('old').map((q) => q * kMm(a));
  const spin = projectionSet('spin').map((q) => q * kMm(a));
  assert.deepEqual(old, spin);
  checks += 1;
  const wrongG = enumerate(0.5).map((m) => 2.1 * m * kMm(a));
  check(Math.abs(wrongG[1] - spin[1]) > 0,
    `trial ${trial} wrong g factor must move the spin result`);
}

const blurred = { ...defaults, slit: 1.5, resolution: 1.5 };
let blurredPeak = 0;
for (let i = 0; i <= 800; i += 1) {
  const x = -8 + 16 * i / 800;
  blurredPeak = Math.max(blurredPeak, density('old', x, blurred));
}
check(density('old', 0, blurred) / blurredPeak > 0.2,
  'large shared blur must make the doublet unresolved');

const staticAnchors = [
  '<title>Stern-Gerlach Experiment: What It Actually Proved</title>',
  'content="https://artwaste.land/og/stern-gerlach.png"',
  '"datePublished":"2026-07-30"',
  '"dateModified":"2026-07-30"',
  'value="1000"',
  'value="500"',
  'value="35"',
  'value="200"',
  'value="0.05"',
  'value="8"',
  'value="0.04"',
  'burst: 240',
  'seed: 19220208',
  '9.2740100657e-24',
  '1.66053906892e-27',
  'silverU: 107.8682',
  'two discrete beams',
  'no evidence for undeflected atoms',
  'arXiv:2301.11343v1',
  'submitted 26 January 2023',
  '379, 673-699 (1924)',
  '13, 953-954 (1925)',
  '56(12), 53-59 (2003)',
  '41, 327-364 (2016)'
];
for (const anchor of staticAnchors) {
  check(html.includes(anchor), `HTML missing source or numeric anchor: ${anchor}`);
}

const metadataAnchors = [
  'date: 2026-07-30',
  'seam: "physical"',
  'href: "/strata/stern-gerlach/"',
  'to: neutrino-endpoint',
  'to: chladni-figures',
  'to: the-ghz-game',
  'draft: false'
];
for (const anchor of metadataAnchors) {
  check(markdown.includes(anchor), `content file missing metadata anchor: ${anchor}`);
}

check(html.endsWith('</html>\n'), 'HTML must end with the closing html tag');
check(html.includes('</script>\n</body>\n</html>'),
  'load-bearing closing script, body, and html tags must be present');

console.log('Stern-Gerlach verification');
console.log(`external anchor muB derived = ${derivedBohrMagneton.toExponential(13)} J/T`);
console.log(`published 2022 CODATA muB = ${source.bohrMagneton.toExponential(10)} J/T`);
console.log(`silver mass proxy = ${silverMass.toExponential(13)} kg`);
console.log(`default lever integral = ${defaultIntegral.toFixed(6)} T*m`);
console.log(`default K = ${defaultK.toFixed(6)} mm/muB`);
console.log(`classical center density = ${centers.classical.toFixed(6)} 1/mm`);
console.log(`old-rule center density = ${centers.old.toExponential(6)} 1/mm`);
console.log(`orbital-only center density = ${centers.orbital.toFixed(6)} 1/mm`);
console.log(`ideal-spin center density = ${centers.spin.toExponential(6)} 1/mm`);
console.log(`modern L=1 center density = ${centers.l1.toFixed(6)} 1/mm`);
console.log(`old-rule positions = ${oldPositions.map((x) => x.toFixed(6)).join(', ')} mm`);
console.log(`ideal-spin positions = ${spinPositions.map((x) => x.toFixed(6)).join(', ')} mm`);
console.log(`random nonzero apparatus profiles checked = 24`);
console.log(`checks passed = ${checks}`);
