import { readFile } from 'node:fs/promises';

const pagePath = new URL('../../public/strata/wu-parity/index.html', import.meta.url);

const anchors = {
  wu1957: {
    alpha: -0.4,
    orientation: 0.6,
    speed: 0.6,
    warmMinutes: 6,
    received: '1957-01-15',
    published: '1957-02-15'
  },
  wauters2010: {
    leading: -1,
    measured: -1.014,
    stat: 0.012,
    syst: 0.016,
    standardModel: -0.987,
    standardModelSigma: 0.009,
    polarizedFraction: 0.928,
    polarizedFractionSigma: 0.004,
    arxivSubmitted: '2010-05-27',
    arxivVersionCount: 1,
    journalPublished: '2010-11-18'
  },
  records: {
    nistExperimentYear: 1956,
    nobelYear: 1957,
    yangShare: 0.5,
    leeShare: 0.5
  }
};

let checks = 0;

function fail(message) {
  throw new Error(message);
}

function assert(condition, message) {
  checks += 1;
  if (!condition) fail(message);
}

function assertEqual(actual, expected, label) {
  checks += 1;
  if (actual !== expected) {
    fail(`${label}: expected ${expected}, got ${actual}`);
  }
}

function assertClose(actual, expected, tolerance, label) {
  checks += 1;
  if (!Number.isFinite(actual) || Math.abs(actual - expected) > tolerance) {
    fail(`${label}: expected ${expected} within ${tolerance}, got ${actual}`);
  }
}

function extractFixtures(html) {
  const match = html.match(
    /<script type="application\/json" id="verified-fixtures">\s*([\s\S]*?)\s*<\/script>/
  );
  assert(Boolean(match), 'verified fixture block is present');
  return JSON.parse(match[1]);
}

function intensity(k, u) {
  return 1 + k * u;
}

function midpointIntegral(fn, a, b, slices = 200000) {
  const width = (b - a) / slices;
  let sum = 0;
  for (let i = 0; i < slices; i += 1) {
    sum += fn(a + (i + 0.5) * width);
  }
  return sum * width;
}

function numericHemisphereResults(k) {
  const forward = midpointIntegral((u) => intensity(k, u), 0, 1);
  const backward = midpointIntegral((u) => intensity(k, u), -1, 0);
  const total = forward + backward;
  const asymmetry = (forward - backward) / total;
  const l1Numerator = midpointIntegral(
    (u) => Math.abs(intensity(k, u) - intensity(k, -u)),
    -1,
    1
  );
  const l1Denominator = midpointIntegral((u) => intensity(k, u), -1, 1);
  return {
    forward,
    backward,
    total,
    asymmetry,
    residual: l1Numerator / l1Denominator
  };
}

function determinant3(matrix) {
  return (
    matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1])
    - matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0])
    + matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0])
  );
}

function multiplyMatrixVector(matrix, vector) {
  return matrix.map((row) => row.reduce((sum, value, index) => sum + value * vector[index], 0));
}

function scaleVector(scale, vector) {
  return vector.map((value) => scale * value);
}

function dot(left, right) {
  return left.reduce((sum, value, index) => sum + value * right[index], 0);
}

function vectorNorm(vector) {
  return Math.sqrt(dot(vector, vector));
}

function nextRandomFactory(seed) {
  let state = seed >>> 0;
  return function nextRandom() {
    state = (1664525 * state + 1013904223) >>> 0;
    return state / 0x100000000;
  };
}

function checkPublishedObject(actual, expected, prefix) {
  for (const [key, value] of Object.entries(expected)) {
    assertEqual(actual[key], value, `${prefix}.${key}`);
  }
}

async function main() {
  const html = await readFile(pagePath, 'utf8');
  const fixture = extractFixtures(html);

  assert(
    html.trimEnd().endsWith('</html>'),
    'page closes with the html tag'
  );
  assert(
    /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html),
    'inline script, body, and html closing tags are in load-bearing order'
  );
  assert(
    html.includes('<title>Wu Experiment and Parity Violation in Cobalt-60 Beta Decay</title>'),
    'search-facing title matches the candidate spec'
  );
  assert(
    html.includes('"datePublished":"2026-07-30"')
      && html.includes('"dateModified":"2026-07-30"'),
    'JSON-LD publication dates are exact'
  );

  checkPublishedObject(fixture.published.wu1957, anchors.wu1957, 'wu1957');
  checkPublishedObject(fixture.published.wauters2010, anchors.wauters2010, 'wauters2010');
  checkPublishedObject(fixture.published.records, anchors.records, 'records');

  assertEqual(fixture.choices.angularBins, 24, 'equal-angle display bin count');
  assertEqual(fixture.choices.wholeSphereNormalization, 2, 'whole-sphere normalization');
  assertEqual(fixture.choices.warmFade, 'linear', 'warm-up interpolation is named');

  const wuRaw = Math.abs(anchors.wu1957.alpha) / anchors.wu1957.orientation;
  const wuRounded = Math.round(wuRaw * 10) / 10;
  assertClose(wuRaw, fixture.derived.wuLowerLimitRaw, 1e-15, '1957 raw lower-limit division');
  assertClose(wuRounded, fixture.derived.wuLowerLimitRounded, 1e-15, '1957 one-decimal wording');

  const combinedMeasurementSigma = Math.hypot(
    anchors.wauters2010.stat,
    anchors.wauters2010.syst
  );
  const measurementLow = anchors.wauters2010.measured - combinedMeasurementSigma;
  const measurementHigh = anchors.wauters2010.measured + combinedMeasurementSigma;
  const modelLow =
    anchors.wauters2010.standardModel - anchors.wauters2010.standardModelSigma;
  const modelHigh =
    anchors.wauters2010.standardModel + anchors.wauters2010.standardModelSigma;
  const centralDifference =
    anchors.wauters2010.measured - anchors.wauters2010.standardModel;
  const combinedComparisonSigma = Math.hypot(
    combinedMeasurementSigma,
    anchors.wauters2010.standardModelSigma
  );
  const separationSigma = Math.abs(centralDifference) / combinedComparisonSigma;

  assertClose(
    combinedMeasurementSigma,
    fixture.derived.combinedMeasurementSigma,
    1e-15,
    '2010 measurement sigma'
  );
  assertClose(measurementLow, fixture.derived.measurementLow, 1e-15, '2010 measurement low');
  assertClose(measurementHigh, fixture.derived.measurementHigh, 1e-15, '2010 measurement high');
  assertClose(modelLow, fixture.derived.modelLow, 1e-15, '2010 model low');
  assertClose(modelHigh, fixture.derived.modelHigh, 1e-15, '2010 model high');
  assertClose(
    centralDifference,
    fixture.derived.centralDifference,
    1e-15,
    '2010 central difference'
  );
  assertClose(
    combinedComparisonSigma,
    fixture.derived.combinedComparisonSigma,
    1e-15,
    'comparison uncertainty'
  );
  assertClose(
    separationSigma,
    fixture.derived.separationSigma,
    1e-15,
    'central separation in sigma'
  );
  assert(
    measurementHigh >= modelLow && modelHigh >= measurementLow,
    'the one-sigma intervals overlap'
  );

  const defaultNumeric = numericHemisphereResults(anchors.wu1957.alpha);
  assertClose(defaultNumeric.forward, fixture.derived.defaultForward, 2e-12, 'default forward integral');
  assertClose(defaultNumeric.backward, fixture.derived.defaultBackward, 2e-12, 'default backward integral');
  assertClose(
    defaultNumeric.asymmetry,
    fixture.derived.defaultHemisphereAsymmetry,
    2e-12,
    'default hemisphere asymmetry'
  );
  assertClose(
    defaultNumeric.residual,
    fixture.derived.defaultMirrorResidual,
    2e-12,
    'default mirror residual'
  );

  for (const k of [-0.99, -0.7, -0.4, -0.123, 0, 0.23, 0.8, 0.99]) {
    const result = numericHemisphereResults(k);
    assertClose(result.forward, 1 + k / 2, 3e-12, `forward integral at k=${k}`);
    assertClose(result.backward, 1 - k / 2, 3e-12, `backward integral at k=${k}`);
    assertClose(result.total, 2, 4e-12, `whole-sphere integral at k=${k}`);
    assertClose(result.asymmetry, k / 2, 3e-12, `hemisphere asymmetry at k=${k}`);
    assertClose(result.residual, Math.abs(k), 3e-12, `L1 mirror residual at k=${k}`);
  }

  const inversion = [
    [-1, 0, 0],
    [0, -1, 0],
    [0, 0, -1]
  ];
  const inversionDeterminant = determinant3(inversion);
  assertEqual(inversionDeterminant, -1, 'spatial inversion determinant');
  const random = nextRandomFactory(0x60c01957);
  for (let trial = 0; trial < 128; trial += 1) {
    const momentum = [random() * 2 - 1, random() * 2 - 1, random() * 2 - 1];
    const spin = [random() * 2 - 1, random() * 2 - 1, random() * 2 - 1];
    const transformedMomentum = multiplyMatrixVector(inversion, momentum);
    const transformedSpin = scaleVector(
      inversionDeterminant,
      multiplyMatrixVector(inversion, spin)
    );
    assertClose(
      vectorNorm(transformedMomentum),
      vectorNorm(momentum),
      1e-14,
      `polar-vector norm trial ${trial}`
    );
    assertClose(
      vectorNorm(transformedSpin),
      vectorNorm(spin),
      1e-14,
      `axial-vector norm trial ${trial}`
    );
    assertClose(
      dot(transformedSpin, transformedMomentum),
      -dot(spin, momentum),
      1e-14,
      `pseudoscalar sign trial ${trial}`
    );
  }

  const factorCases = [
    { f:1, speed:0.6, A:-1, P:0.6, warm:1, q:1, expected:-0.36 },
    { f:0.928, speed:0.6, A:-0.987, P:0.6, warm:1, q:0.8, expected:null },
    { f:1, speed:1, A:0, P:1, warm:1, q:1, expected:0 },
    { f:1, speed:1, A:-1, P:0, warm:1, q:1, expected:0 },
    { f:1, speed:0, A:-1, P:1, warm:1, q:1, expected:0 },
    { f:0, speed:1, A:-1, P:1, warm:1, q:1, expected:0 },
    { f:1, speed:1, A:-1, P:1, warm:1, q:0, expected:0 },
    { f:1, speed:1, A:-1, P:1, warm:0, q:1, expected:0 }
  ];
  for (const [index, item] of factorCases.entries()) {
    const slope = item.f * item.speed * item.A * item.P * item.warm * item.q;
    if (item.expected !== null) {
      assertClose(slope, item.expected, 1e-15, `factor product case ${index}`);
    }
    const result = numericHemisphereResults(slope);
    assertClose(result.asymmetry, slope / 2, 3e-12, `factor asymmetry case ${index}`);
  }

  for (const angleDegrees of [0, 30, 60, 90, 120, 150, 180]) {
    const u = Math.cos((angleDegrees * Math.PI) / 180);
    const pairedDifference =
      intensity(anchors.wu1957.alpha, u) - intensity(anchors.wu1957.alpha, -u);
    assertClose(
      pairedDifference,
      2 * anchors.wu1957.alpha * u,
      1e-15,
      `matched-angle difference at ${angleDegrees} degrees`
    );
  }
  assertClose(
    intensity(anchors.wu1957.alpha, 0) - intensity(anchors.wu1957.alpha, -0),
    0,
    0,
    'theta 90 degrees is blind'
  );

  const requiredSources = [
    'https://doi.org/10.1103/PhysRev.105.1413',
    'https://doi.org/10.1103/PhysRev.104.254',
    'https://arxiv.org/abs/1005.5034',
    'https://www.nist.gov/pml/fall-parity/reversal-parity-law-nuclear-physics',
    'https://www.nobelprize.org/prizes/physics/1957/summary/'
  ];
  for (const source of requiredSources) {
    assert(html.includes(source), `source link is surfaced: ${source}`);
  }

  console.log('Wu 1957 source-audited inputs:');
  console.log(`  alpha = ${anchors.wu1957.alpha.toFixed(1)}`);
  console.log(`  orientation = ${anchors.wu1957.orientation.toFixed(1)}`);
  console.log(`  speed ratio = ${anchors.wu1957.speed.toFixed(1)}`);
  console.log(`  lower-limit arithmetic = ${wuRaw.toFixed(6)} -> about ${wuRounded.toFixed(1)}`);
  console.log(`  warm-up wording = about ${anchors.wu1957.warmMinutes} minutes`);
  console.log('Default distribution:');
  console.log(`  forward = ${defaultNumeric.forward.toFixed(6)}`);
  console.log(`  backward = ${defaultNumeric.backward.toFixed(6)}`);
  console.log(`  hemisphere asymmetry = ${defaultNumeric.asymmetry.toFixed(6)}`);
  console.log(`  normalized L1 mirror residual = ${defaultNumeric.residual.toFixed(6)}`);
  console.log('Wauters 2010 source-audited inputs and derived comparison:');
  console.log(
    `  measured = ${anchors.wauters2010.measured.toFixed(3)} `
      + `(${anchors.wauters2010.stat.toFixed(3)} stat, `
      + `${anchors.wauters2010.syst.toFixed(3)} syst)`
  );
  console.log(`  combined measurement sigma = ${combinedMeasurementSigma.toFixed(3)}`);
  console.log(
    `  measured one-sigma interval = [${measurementLow.toFixed(3)}, ${measurementHigh.toFixed(3)}]`
  );
  console.log(
    `  recoil-corrected model interval = [${modelLow.toFixed(3)}, ${modelHigh.toFixed(3)}]`
  );
  console.log(`  central separation = ${separationSigma.toFixed(6)} sigma`);
  console.log(`  published polarized fraction = ${anchors.wauters2010.polarizedFraction.toFixed(3)}(4)`);
  console.log(`Parity transform random-vector trials: 128`);
  console.log(`Checks passed: ${checks}`);
  console.log('No checks skipped.');
}

main().catch((error) => {
  console.error(`FAIL: ${error.message}`);
  process.exit(1);
});
