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

const here = path.dirname(fileURLToPath(import.meta.url));
const htmlPath = path.resolve(here, '../../public/strata/the-distance-in-its-legs/index.html');
const mdPath = path.resolve(here, '../../src/content/strata/the-distance-in-its-legs.md');
const html = fs.readFileSync(htmlPath, 'utf8');
const markdown = fs.readFileSync(mdPath, 'utf8');
const text = html
  .replace(/<script[\s\S]*?<\/script>/gi, ' ')
  .replace(/<style[\s\S]*?<\/style>/gi, ' ')
  .replace(/<!--[\s\S]*?-->/g, ' ')
  .replace(/<[^>]*>/g, ' ');

let failures = 0;
function report(label, pass, detail = '') {
  const mark = pass ? 'PASS' : 'FAIL';
  const renderedDetail = typeof detail === 'string' ? detail : JSON.stringify(detail);
  process.stdout.write(`${mark}  ${label}${renderedDetail ? ` | ${renderedDetail}` : ''}\n`);
  if (!pass) failures += 1;
}

function shows(label, computed, decimals) {
  const rendered = computed.toFixed(decimals);
  report(`page displays ${label} as ${rendered}`, text.includes(rendered), { computed, rendered });
}

function close(a, b, tolerance = 1e-9) {
  return Math.abs(a - b) <= tolerance;
}

function medianBySort(values) {
  const a = values.slice().sort((x, y) => x - y);
  const middle = Math.floor(a.length / 2);
  return a.length % 2 ? a[middle] : (a[middle - 1] + a[middle]) / 2;
}

// Independent median route: remove successive minima without sorting or calling route A.
function medianBySelection(values) {
  const pool = values.slice();
  const picked = [];
  while (picked.length <= Math.floor(values.length / 2)) {
    let at = 0;
    for (let i = 1; i < pool.length; i += 1) if (pool[i] < pool[at]) at = i;
    picked.push(pool[at]);
    pool.splice(at, 1);
  }
  const middle = Math.floor(values.length / 2);
  return values.length % 2 ? picked[middle] : (picked[middle - 1] + picked[middle]) / 2;
}

function quantileInclusive(values, probability) {
  const a = values.slice().sort((x, y) => x - y);
  const position = (a.length - 1) * probability;
  const low = Math.floor(position);
  const high = Math.min(low + 1, a.length - 1);
  return a[low] + (a[high] - a[low]) * (position - low);
}

function stridePredictionRatio(trainMetres, outboundMm, inboundMm) {
  return trainMetres * inboundMm / outboundMm;
}

function stridePredictionCount(trainMetres, outboundMm, inboundMm) {
  const encodedStrides = trainMetres * 1000 / outboundMm;
  return encodedStrides * inboundMm / 1000;
}

function extractScript(id, type) {
  const pattern = new RegExp(`<script[^>]*type=["']${type}["'][^>]*id=["']${id}["'][^>]*>([\\s\\S]*?)<\\/script>`);
  const match = html.match(pattern);
  if (!match) throw new Error(`Could not find script ${id}`);
  return JSON.parse(match[1]);
}

const raw = extractScript('raw-turning-data', 'application/json');
const source = extractScript('source-constants', 'application/json');
const ldMatch = html.match(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/);
const jsonLd = ldMatch ? JSON.parse(ldMatch[1]) : null;

const allRows = Object.values(raw).flat();
const missing = allRows.reduce((sum, row) => sum + row.filter((v) => !Number.isFinite(v)).length, 0);
report('2018 workbook row count', allRows.length === 249, `found ${allRows.length}, expected 249`);
report('2018 workbook missing-value count', missing === 0, `found ${missing}, expected 0`);
report('each raw row has six turning points', allRows.every((row) => row.length === 6));

const groupSummaries = {};
for (const [group, rows] of Object.entries(raw)) {
  const centresA = rows.map((row) => medianBySort(row.slice(1, 6)));
  const centresB = rows.map((row) => medianBySelection(row.slice(1, 6)));
  const grandA = medianBySort(centresA);
  const grandB = medianBySelection(centresB);
  groupSummaries[group] = {
    n: rows.length,
    centre: grandA,
    first: medianBySort(rows.map((row) => row[0])),
    q1: quantileInclusive(centresA, 0.25),
    q3: quantileInclusive(centresA, 0.75),
  };
  report(`independent raw median routes agree for ${group}`, close(grandA, grandB), `${grandA.toFixed(2)} m`);
}

for (const [group, published] of Object.entries(source.published2018)) {
  const computed = groupSummaries[group].centre;
  report(`published median anchor ${group}`, close(computed, published.median, 0.005), `raw ${computed.toFixed(2)} m, paper ${published.median.toFixed(2)} m`);
}

report('1-11 count mismatch is exposed', raw['1-11'].length === 37 && source.published2018['1-11'].n === 26,
  `workbook ${raw['1-11'].length}, article ${source.published2018['1-11'].n}`);

const normal = source.stridesMm.normal;
const stilt = source.stridesMm.stilt;
const stump = source.stridesMm.stump;
const stiltA = stridePredictionRatio(source.trainMetres, normal, stilt);
const stiltB = stridePredictionCount(source.trainMetres, normal, stilt);
const stumpA = stridePredictionRatio(source.trainMetres, normal, stump);
const stumpB = stridePredictionCount(source.trainMetres, normal, stump);
report('independent stride routes agree for stilts', close(stiltA, stiltB), `${stiltA.toFixed(5)} m`);
report('independent stride routes agree for stumps', close(stumpA, stumpB), `${stumpA.toFixed(5)} m`);

const sameStrideAnchor = stridePredictionCount(source.trainMetres, stilt, stilt);
report('closed-form same-stride anchor returns 10 m', close(sameStrideAnchor, 10), `${sameStrideAnchor.toFixed(2)} m`);

const sensitivitySweep = [0.8, 1, 1.4];
const cancellationSweep = Object.values(source.stridesMm).every((stride) => sensitivitySweep.every((factor) => {
  const effectiveStride = stride * factor;
  return close(stridePredictionCount(source.trainMetres, effectiveStride, effectiveStride), 10);
}));
report('same-legs cancellation holds across every reader-reachable sensitivity extreme', cancellationSweep);

const poisonedOutbound = normal * 1.20;
const poisoned = stridePredictionCount(source.trainMetres, poisonedOutbound, stilt);
const poisonRejected = !close(poisoned, stiltA, 0.01);
report('control rejects a 20 percent corrupted outbound stride', poisonRejected,
  `clean ${stiltA.toFixed(2)} m, poisoned ${poisoned.toFixed(2)} m`);

const poisonedRaw = raw['0-10'].map((row) => row.map((v) => v + 4));
const poisonedCentres = poisonedRaw.map((row) => medianBySelection(row.slice(1, 6)));
const poisonedMedian = medianBySelection(poisonedCentres);
const rawPoisonRejected = !close(poisonedMedian, source.published2018['0-10'].median, 0.005);
report('control rejects deliberately shifted 0-10 raw data', rawPoisonRejected,
  `paper ${source.published2018['0-10'].median.toFixed(2)} m, poisoned ${poisonedMedian.toFixed(2)} m`);

const opticWeight = 1 - groupSummaries['0-11'].centre / source.trainMetres;
const fixedAdditive = groupSummaries['0-10'].first + opticWeight * source.trainMetres;
const additiveResidual = groupSummaries['0-10'].centre - fixedAdditive;

const figures = {
  'normal-prediction': stridePredictionCount(10, normal, normal).toFixed(2),
  'stilt-prediction': stiltA.toFixed(2),
  'stump-prediction': stumpA.toFixed(2),
  'raw-row-count': String(allRows.length),
  'raw-missing-count': String(missing),
  'zero-ten-first': groupSummaries['0-10'].first.toFixed(2),
  'zero-ten-centre': groupSummaries['0-10'].centre.toFixed(2),
  'fixed-additive': fixedAdditive.toFixed(2),
  'additive-residual': additiveResidual.toFixed(2),
  'median-max-error': Math.max(...Object.entries(source.published2018).map(([group, p]) => Math.abs(groupSummaries[group].centre - p.median))).toFixed(2),
};
for (const [key, value] of Object.entries(figures)) {
  const escaped = value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  report(`rendered fallback figure ${key}`, new RegExp(`data-verified="${key}"[^>]*>${escaped}<`).test(html), value);
}

report('source stride constants appear on the visible page',
  ['14.8', '13.0', '8.6', '0.29', '0.31', '0.14', '14.25'].every((value) => html.includes(`data-source-value="${value}"`)));
report('2006 observed medians appear on the visible page',
  ['15.30', '10.20', '5.75', '10.55', '10.25'].every((value) => html.includes(`data-observed-value="${value}"`)));
shows('published speed-corrected stilt prediction', source.published2006.speedCorrectedStiltPrediction, 2);
shows('published first-test stilt median', source.observed2006.stilt.after, 2);
shows('published second-test stilt median', source.observed2006.stilt.both, 2);
shows('published second-test stump median', source.observed2006.stump.both, 2);
report('2006 source IQR widths and sample size appear on the visible page',
  ['2.40 m', '3.24 m', '1.81 m', '1.45 m', '1.76 m'].every((value) => html.includes(value)) && html.includes('25 ants in each group'));

const expectedDek = 'A desert ant learns a 10 metre route, then searches too far on lengthened legs and too soon on shortened ones. Recompute the stride-integrator prediction against the 2006 medians, then work through 249 raw records from a later experiment in which stride and ventral optic-flow memories are blocked and restored at different moments.';
report('frontmatter dek matches meta description', markdown.includes(`dek: "${expectedDek}"`) && html.includes(`<meta name="description" content="${expectedDek}"`));
report('frontmatter SEO title matches HTML title',
  markdown.includes('seoTitle: "Desert Ant Odometer: Stilts, Stumps, and Optic Flow"') && html.includes('<title>Desert Ant Odometer: Stilts, Stumps, and Optic Flow</title>'));
report('canonical URL is correct', html.includes('https://artwaste.land/strata/the-distance-in-its-legs/'));
report('JSON-LD parses with Article fields', jsonLd && jsonLd['@type'] === 'Article' && jsonLd.headline === 'The Distance in Its Legs' && jsonLd.datePublished === '2026-08-25' && jsonLd.dateModified === '2026-08-25');
report('frontmatter date and publication state are correct', markdown.includes('date: 2026-08-25') && markdown.includes('draft: false'));
report('load-bearing closing tags are present', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));

// The same figure is also stated a second time in bare prose, with no attribute beside it,
// and that copy was the one nothing watched. Assert that EVERY visible occurrence of the
// speed-corrected prediction reads the source value, so the prose cannot drift from the
// element that carries the data attribute.
{
  const visible = html
    .replace(/<script[\s\S]*?<\/script>/gi, ' ')
    .replace(/<style[\s\S]*?<\/style>/gi, ' ')
    .replace(/<!--[\s\S]*?-->/g, ' ')
    .replace(/<[^>]*>/g, ' ');
  const correct = source.published2006.speedCorrectedStiltPrediction.toFixed(2);
  // Any number printed immediately before " m corrected" or " m stilt" style prose, plus
  // every standalone two-decimal figure in the same sentence, must be the source value.
  const proseHits = [...visible.matchAll(/(\d+\.\d{2}) m corrected/g)].map((m) => m[1]);
  report(`every prose mention of the corrected stilt result reads ${correct} (${proseHits.length} found)`,
    proseHits.length > 0 && proseHits.every((v) => v === correct), proseHits);
}

// ⚠ THE PAGE KEEPS EVERY FIGURE TWICE, and only one copy was checked.
// Each measured value appears both as a data-observed-value / data-source-value ATTRIBUTE
// and as the visible text of the same element. Every assertion above matches the attribute,
// so corrupting the TEXT left the whole verifier green while the reader saw a different
// number. Caught 2026-08-25 by mutating the rendered text: 0 of 5 corruptions were noticed.
// A page that states a figure twice must assert that the two copies agree, or the pair can
// silently drift and nothing is watching the half the reader actually reads.
const pairRe = /<[^>]*data-(?:observed|source)-value="([^"]+)"[^>]*>([^<]*)</g;
let pairs = 0;
let mismatched = [];
for (const m of html.matchAll(pairRe)) {
  pairs += 1;
  const attr = m[1].trim();
  const shown = m[2].trim();
  // The visible text carries a unit, e.g. attribute "15.30" shown as "15.30 m".
  if (!shown.startsWith(attr)) mismatched.push(`${attr} vs rendered "${shown}"`);
}
report(`every data-value attribute agrees with its own rendered text (${pairs} pairs)`,
  pairs > 0 && mismatched.length === 0, mismatched.slice(0, 5));

if (failures) {
  process.stderr.write(`\n${failures} verification check(s) failed.\n`);
  process.exit(1);
}
process.stdout.write('\nAll verification checks passed.\n');
