import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const htmlPath = path.join(
  root,
  'public/strata/the-blowup-you-must-hit-exactly/index.html'
);
const html = fs.readFileSync(htmlPath, 'utf8');

let failures = 0;
function assert(name, condition, detail = '') {
  if (condition) {
    console.log(`PASS ${name}${detail ? `: ${detail}` : ''}`);
  } else {
    failures += 1;
    console.error(`FAIL ${name}${detail ? `: ${detail}` : ''}`);
  }
}
function close(actual, expected, relativeTolerance = 2e-12, absoluteTolerance = 1e-14) {
  const difference = Math.abs(actual - expected);
  return difference <= absoluteTolerance ||
    difference <= relativeTolerance * Math.max(Math.abs(actual), Math.abs(expected));
}

const startMarker = '/* VERIFY_EXPORTS_START */';
const endMarker = '/* VERIFY_EXPORTS_END */';
const start = html.indexOf(startMarker);
const end = html.indexOf(endMarker);
assert('shipped verification block exists', start >= 0 && end > start);

const shippedSource = html.slice(start + startMarker.length, end);
function loadShipped(source) {
  return Function(
    `${source}
    return { IPM_DATA, SEPTEMBER_RESIDUALS, scaling, regression,
      septemberEstimate, ordinaryResidual };`
  )();
}
const shipped = loadShipped(shippedSource);

const paperLambdas = [
  [0, 1.0285722760323, 1e-13],
  [1, 0.472129736156, 2e-12],
  [2, 0.3149617817, 3e-10],
  [3, 0.24156641, 1e-8],
  [4, 0.1987237, 1e-7]
];
const paperResiduals = [
  ['boundary IPM', 'stable', -11.183],
  ['boundary IPM', 'first unstable', -10.510],
  ['boundary IPM', 'second unstable', -8.101],
  ['boundary IPM', 'third unstable', -7.526],
  ['2D Boussinesq', 'stable', -8.178],
  ['2D Boussinesq', 'first unstable', -8.038],
  ['2D Boussinesq', 'second unstable', -7.772],
  ['2D Boussinesq', 'third unstable', -7.558],
  ['2D Boussinesq', 'fourth candidate, unvalidated', -7.020]
];

assert(
  'Figure 7f published lambda table',
  shipped.IPM_DATA.length === paperLambdas.length &&
    paperLambdas.every(([n, lambda, uncertainty], index) => {
      const actual = shipped.IPM_DATA[index];
      return actual.n === n && actual.lambda === lambda &&
        actual.uncertainty === uncertainty;
    }),
  'all five values and reported uncertainties match arXiv:2511.22819v1'
);
assert(
  'Figure 3b published residual table',
  shipped.SEPTEMBER_RESIDUALS.length === paperResiduals.length &&
    paperResiduals.every(([system, mode, log10], index) => {
      const actual = shipped.SEPTEMBER_RESIDUALS[index];
      return actual.system === system && actual.mode === mode &&
        actual.log10 === log10;
    }),
  'all nine log10 values match arXiv:2509.14185v1'
);

function referenceScaling(stepIndex, lambda) {
  const exponent = stepIndex / 100;
  const logTau = -exponent * Math.LN10;
  const tau = Math.exp(logTau);
  const length = Math.exp((1 + lambda) * logTau);
  const amplitude = Math.exp(lambda * logTau);
  return {
    tau,
    time: 1 - tau,
    length,
    amplitude,
    gradient: Math.exp(-logTau),
    inverseTime: Math.exp(-logTau)
  };
}

let scalingCases = 0;
let scalingPass = true;
for (const [, lambda] of paperLambdas) {
  for (let step = 0; step <= 800; step += 1) {
    const exponent = step / 100;
    const actual = shipped.scaling(exponent, lambda);
    const expected = referenceScaling(step, lambda);
    scalingCases += 1;
    for (const key of ['tau', 'time', 'length', 'amplitude', 'gradient', 'inverseTime']) {
      if (!close(actual[key], expected[key], 8e-12, 2e-14)) {
        scalingPass = false;
      }
    }
  }
}
assert(
  'every reachable clock value against independent log-space reference',
  scalingPass,
  `${scalingCases} mode and slider combinations`
);

function referenceRegression(points) {
  const xs = points.map((point) => point.n);
  const ys = points.map((point) => 1 / point.lambda);
  const meanX = xs.reduce((sum, value) => sum + value, 0) / xs.length;
  const meanY = ys.reduce((sum, value) => sum + value, 0) / ys.length;
  const centeredCross = xs.reduce(
    (sum, value, index) => sum + (value - meanX) * (ys[index] - meanY),
    0
  );
  const centeredX = xs.reduce(
    (sum, value) => sum + (value - meanX) ** 2,
    0
  );
  const slope = centeredCross / centeredX;
  const intercept = meanY - slope * meanX;
  const rows = points.map((point) => {
    const observed = 1 / point.lambda;
    const fitted = intercept + slope * point.n;
    return { n: point.n, observed, fitted, residual: observed - fitted };
  });
  const ssResidual = rows.reduce((sum, row) => sum + row.residual ** 2, 0);
  const ssTotal = ys.reduce((sum, value) => sum + (value - meanY) ** 2, 0);
  return {
    intercept,
    slope,
    r2: 1 - ssResidual / ssTotal,
    rows,
    lambdaAt4: 1 / (intercept + 4 * slope)
  };
}

let regressionPass = true;
for (const count of [4, 5]) {
  const points = shipped.IPM_DATA.slice(0, count);
  const actual = shipped.regression(points);
  const expected = referenceRegression(points);
  for (const key of ['intercept', 'slope', 'r2', 'lambdaAt4']) {
    regressionPass &&= close(actual[key], expected[key], 2e-12, 1e-14);
  }
  actual.rows.forEach((row, index) => {
    for (const key of ['observed', 'fitted', 'residual']) {
      regressionPass &&= close(row[key], expected.rows[index][key], 3e-12, 1e-14);
    }
  });
}
assert(
  'both reachable regressions against independent centered OLS',
  regressionPass,
  'four-point and five-point settings'
);

let conversionPass = true;
for (const [, , log10] of paperResiduals) {
  const expected = Math.exp(log10 * Math.LN10);
  conversionPass &&= close(
    shipped.ordinaryResidual(log10),
    expected,
    2e-12,
    1e-16
  );
}
assert(
  'all published log10 residuals converted independently',
  conversionPass,
  `${paperResiduals.length} conversions`
);

let septemberPass = true;
for (let n = 0; n <= 4; n += 1) {
  const expected = 10000 / (11459 * n + 9723);
  septemberPass &&= close(shipped.septemberEstimate(n), expected);
}
assert(
  'September empirical rule implementation',
  septemberPass,
  'five displayed instability orders'
);

const mutatedSource = shippedSource.replace(
  'var length = Math.pow(tau, 1 + lambda);',
  'var length = Math.pow(tau, 1 - lambda);'
);
assert('mutation was applied to extracted page copy', mutatedSource !== shippedSource);
const mutated = loadShipped(mutatedSource);
let mutationCaught = false;
for (const [, lambda] of paperLambdas) {
  for (let step = 1; step <= 800; step += 1) {
    const actual = mutated.scaling(step / 100, lambda);
    const expected = referenceScaling(step, lambda);
    if (!close(actual.length, expected.length, 8e-12, 2e-14)) {
      mutationCaught = true;
      break;
    }
  }
  if (mutationCaught) break;
}
assert(
  'deliberate in-memory page mutation makes differential check fail',
  mutationCaught,
  'changed 1 + lambda to 1 - lambda, detected, then discarded'
);

assert(
  'proof status keeps new IPM work below rigorous enclosure',
  html.includes("var ipmPasses = threshold <= 1;") &&
    html.includes("var chenPasses = threshold <= 3;")
);
assert(
  'accessibility hooks present',
  /<label[^>]+for="mode-select"/.test(html) &&
    /<label[^>]+for="time-control"/.test(html) &&
    /<label[^>]+for="include-fourth"/.test(html) &&
    /<label[^>]+for="proof-control"/.test(html) &&
    html.includes('aria-live="polite"') &&
    html.includes('@media (prefers-reduced-motion:reduce)') &&
    html.includes(':focus-visible')
);
assert(
  'load-bearing closing tags present',
  html.trimEnd().endsWith('</body>\n</html>')
);
assert(
  'no em dash in shipped artifact',
  !html.includes('\u2014')
);

if (failures > 0) {
  console.error(`FAILED ${failures} assertion${failures === 1 ? '' : 's'}`);
  process.exit(1);
}
console.log('PASS verifier completed with zero failures');
