// verify.mjs: checks for /strata/the-mound-that-breathes/.
// Run: node research/the-mound-that-breathes/verify.mjs
//
// It imports the page's own engine (public/strata/the-mound-that-breathes/engine.mjs) and
// the page's own data (data.json), and holds what the page says against things computed
// another way: the heat equation stepped forward in time on a grid (flat ground and a
// cylinder), a Fourier transform taken straight off the plotted points with no resampling,
// the sources' own arithmetic redone, and the page's printed numbers read back out of its
// HTML. No network needed.
//
// ENGINE=<path> points it at another engine file; mutate.mjs uses that to check that a
// broken engine makes this fail.

import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
import * as PageEngine from '../../public/strata/the-mound-that-breathes/engine.mjs';

const E = process.env.ENGINE ? await import(pathToFileURL(process.env.ENGINE).href) : PageEngine;
const PAGE = new URL('../../public/strata/the-mound-that-breathes/', import.meta.url);
const data = JSON.parse(readFileSync(new URL('data.json', PAGE), 'utf8'));
const fig = JSON.parse(readFileSync(new URL('./data/ocko2017-fig2b.json', import.meta.url), 'utf8'));

let pass = 0, fail = 0;
const lines = [];
function ok(name, cond, detail = '') {
  cond ? pass++ : fail++;
  lines.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  :  ' + detail : ''}`);
}
const head = (t) => lines.push('', `-- ${t}`);
const fx = (v, d = 3) => Number(v).toFixed(d);
const DAY = 86400, W = 2 * Math.PI / DAY;

// ---------------------------------------------------------------------------
head('1. The daily wave in flat ground: closed form against the heat equation on a grid');
{
  // Explicit finite differences, 4 m of ground, 1 cm cells, surface held to a two-harmonic
  // day, bottom insulated, run for 40 days so the start is forgotten, then compare the last
  // day at three depths with the engine's harmonic-by-harmonic formula.
  const kappa = 0.5e-6, dx = 0.01, n = 400, dt = 0.4 * dx * dx / kappa;
  const surf = (t) => 20 + 8 * Math.cos(W * t - 2.2) + 2.5 * Math.cos(2 * W * t - 0.7);
  let T = new Float64Array(n + 1).fill(20), t = 0;
  const steps = Math.round(DAY / dt), dtx = DAY / steps;
  const lam = kappa * dtx / (dx * dx);
  const probes = [5, 20, 50].map((cm) => ({ cm, got: [] }));
  for (let day = 0; day < 40; day++) {
    for (let s = 0; s < steps; s++) {
      const N = new Float64Array(n + 1);
      N[0] = surf(t + dtx);
      for (let i = 1; i < n; i++) N[i] = T[i] + lam * (T[i + 1] - 2 * T[i] + T[i - 1]);
      N[n] = N[n - 1];
      T = N; t += dtx;
      if (day === 39 && s % Math.round(steps / 48) === 0) for (const p of probes) p.got.push([t % DAY, T[p.cm]]);
    }
  }
  const M = 480, samples = [];
  for (let k = 0; k < M; k++) samples.push(surf(k * DAY / M));
  const c = E.fourier(samples, 4);
  let worst = 0; const row = [];
  for (const p of probes) {
    const cx = E.atDepth(c, p.cm / 100, kappa);
    let w = 0;
    for (const [tt, v] of p.got) w = Math.max(w, Math.abs(E.evalSeries(cx, tt) - v));
    worst = Math.max(worst, w);
    row.push(`${p.cm} cm: ${fx(w, 3)} degC`);
  }
  ok('the engine\'s damped, delayed harmonics match the grid solution at 5, 20 and 50 cm', worst < 0.03, row.join('; '));
  ok('penetration depth of the daily wave at kappa = 0.5 mm²/s is 11.7 cm', Math.abs(E.depth(0.5e-6) - 0.1173) < 0.0005, fx(E.depth(0.5e-6) * 100, 2) + ' cm');
  const yr = E.depth(0.5e-6, 1, 365.25 * DAY);
  ok('and of the yearly wave, 2.24 m (sqrt(365.25) times deeper)', Math.abs(yr - 2.241) < 0.005 && Math.abs(yr / E.depth(0.5e-6) - Math.sqrt(365.25)) < 1e-9, fx(yr, 3) + ' m');
}

// ---------------------------------------------------------------------------
head('2. A body warmed from every side: the cylinder formula against a grid');
{
  // Radial heat equation in a long cylinder, surface held to cos(wt), run to steady cycling,
  // read the axis. Compare size and delay with the engine's 1/I0((1+i)R/d).
  const kappa = 0.5e-6, d = E.depth(kappa);
  for (const rd of [0.8, 1.6]) {
    const R = rd * d, n = 80, dr = R / n, dt = 0.2 * dr * dr / kappa;
    const steps = Math.ceil(DAY / dt), dtx = DAY / steps, lam = kappa * dtx / (dr * dr);
    let T = new Float64Array(n + 1), t = 0, axis = [];
    for (let day = 0; day < 12; day++) {
      for (let s = 0; s < steps; s++) {
        const N = new Float64Array(n + 1);
        N[0] = T[0] + 4 * lam * (T[1] - T[0]);
        for (let i = 1; i < n; i++) N[i] = T[i] + lam * ((1 + 1 / (2 * i)) * T[i + 1] - 2 * T[i] + (1 - 1 / (2 * i)) * T[i - 1]);
        t += dtx; N[n] = Math.cos(W * t); T = N;
        if (day === 11) axis.push([t % DAY, T[0]]);
      }
    }
    let re = 0, im = 0;
    for (const [tt, v] of axis) { re += v * Math.cos(W * tt); im += v * Math.sin(W * tt); }
    re *= 2 / axis.length; im *= 2 / axis.length;
    const gridDamp = Math.hypot(re, im), gridDelay = Math.atan2(im, re);
    const e = E.dampDelay(E.response('cylinder', rd));
    ok(`axis of a cylinder of radius ${rd} penetration depths: size and delay match the grid`,
      Math.abs(gridDamp - e.damp) < 0.01 && Math.abs(gridDelay - e.delay) < 0.02,
      `grid ${fx(gridDamp)} / ${fx(gridDelay)} rad; formula ${fx(e.damp)} / ${fx(e.delay)} rad`);
  }
  // Flat ground: size is exactly e^-delay. A body heated all round is always less damped.
  let flatWorst = 0;
  for (const r of [0.2, 0.7, 1.3, 2.5]) { const f = E.dampDelay(E.response('flat', r)); flatWorst = Math.max(flatWorst, Math.abs(f.damp - Math.exp(-f.delay))); }
  ok('in flat ground the damping is exactly e to the minus the delay', flatWorst < 1e-12, `worst ${flatWorst.toExponential(1)}`);
  const at = (s) => E.dampDelay(E.response(s, E.rForDelay(s, 0.656))).damp;
  ok('for the same 0.656 rad delay: flat 0.519 < slab 0.865 < cylinder 0.898', Math.abs(at('flat') - 0.519) < 0.001 && Math.abs(at('slab') - 0.865) < 0.001 && Math.abs(at('cylinder') - 0.898) < 0.001,
    `${fx(at('flat'))}, ${fx(at('slab'))}, ${fx(at('cylinder'))}`);
}

// ---------------------------------------------------------------------------
head('3. The curves read out of Ocko et al. 2017, Fig. 2B');
{
  const names = Object.keys(data.ocko2017.curves).sort();
  ok('seven curves, the same as the extraction wrote', names.join() === 'center,east,nest,north,south,top,west' && JSON.stringify(data.ocko2017.curves) === JSON.stringify(fig.curves), names.join(', '));
  let monotone = true, span = true;
  for (const n of names) {
    const p = data.ocko2017.curves[n];
    for (let k = 1; k < p.length; k++) if (p[k][0] < p[k - 1][0]) monotone = false;
    if (p[0][0] > 0.05 || p[p.length - 1][0] < 23.95) span = false;
  }
  ok('every curve runs forward in time and covers the whole day', monotone && span);
  // Independent Fourier: integrate cos and sin against the piecewise-linear curve exactly,
  // segment by segment, with no resampling and with the end-to-end drift removed the same way.
  function exactFundamental(p0) {
    // The engine holds a curve flat before its first and after its last point; do the same,
    // so both read the same function on [0, 24].
    const p = [[0, p0[0][1]], ...p0, [24, p0[p0.length - 1][1]]];
    const drift = p[p.length - 1][1] - p[0][1];
    const f = (h, v) => v - drift * (h / 24 - 0.5);
    let a = 0, b = 0, m = 0;
    for (let k = 0; k < p.length - 1; k++) {
      const [h0, v0] = p[k], [h1, v1] = p[k + 1];
      if (h1 <= h0) continue;
      const S = 64;
      for (let j = 0; j < S; j++) {
        const u = (j + 0.5) / S, h = h0 + (h1 - h0) * u, v = f(h, v0 + (v1 - v0) * u), dh = (h1 - h0) / S;
        a += v * Math.cos(2 * Math.PI * h / 24) * dh; b += v * Math.sin(2 * Math.PI * h / 24) * dh; m += v * dh;
      }
    }
    return { mean: m / 24, amp: Math.hypot(a, b) * 2 / 24 };
  }
  let worst = 0; const row = [];
  for (const n of names) {
    const x = exactFundamental(data.ocko2017.curves[n]), s = E.curveStats(data.ocko2017.curves[n]);
    worst = Math.max(worst, Math.abs(x.amp - s.amp), Math.abs(x.mean - s.mean));
    row.push(`${n} ${fx(s.amp, 2)}/${fx(x.amp, 2)}`);
  }
  ok('the daily swing of each curve, resampled vs integrated straight off the plotted segments, agree to 0.01 degC', worst < 0.01, row.join('; '));
}

const A = E.analyse(data, 0.5e-6);

// ---------------------------------------------------------------------------
head('4. What the readings say');
{
  const s = A.stats;
  ok('the sides average 26.4 degC and swing ±5.6 degC, warmest at 16:46', Math.abs(A.periphery.mean - 26.42) < 0.02 && Math.abs(A.periphery.amp - 5.59) < 0.02 && Math.abs(A.periphery.peak - 16.76) < 0.02,
    `${fx(A.periphery.mean, 2)} ± ${fx(A.periphery.amp, 2)}, peak ${fx(A.periphery.peak, 2)} h`);
  ok('the centre averages 28.4 and swings ±3.75, warmest at 19:16', Math.abs(s.center.mean - 28.42) < 0.02 && Math.abs(s.center.amp - 3.75) < 0.02 && Math.abs(s.center.peak - 19.26) < 0.02,
    `${fx(s.center.mean, 2)} ± ${fx(s.center.amp, 2)}, peak ${fx(s.center.peak, 2)} h`);
  ok('the nest averages 29.6 and its daily wave is 0.10 degC, a fifth of the logger\'s stated 0.5 degC accuracy', Math.abs(s.nest.mean - 29.65) < 0.02 && s.nest.amp < 0.15,
    `${fx(s.nest.mean, 2)} ± ${fx(s.nest.amp, 2)}`);
  const lo = Math.min(...data.ocko2017.curves.nest.map((p) => p[1])), hi = Math.max(...data.ocko2017.curves.nest.map((p) => p[1]));
  ok('the whole plotted nest trace spans 1.2 degC (29.2 to 30.4), most of it a slow drift', Math.abs(lo - 29.17) < 0.02 && Math.abs(hi - 30.35) < 0.02, `${fx(lo, 2)} to ${fx(hi, 2)}`);
  ok('the nest keeps 1.7% of the sides\' daily swing', Math.abs(A.nest.ratio - 0.0173) < 0.001, fx(A.nest.ratio, 4));
  const [c1, c2] = A.crossings;
  ok('sides minus centre changes sign twice: up through zero at 09:23, down at 17:27',
    A.crossings.length === 2 && c1.dir === 1 && c2.dir === -1 && Math.abs(c1.hour - 9.38) < 0.02 && Math.abs(c2.hour - 17.44) < 0.02,
    A.crossings.map((c) => `${fx(c.hour, 3)} h (${c.dir > 0 ? 'up' : 'down'})`).join(', '));
  ok('and runs from -5.1 degC (night: sides colder) to +1.7 degC (day: sides warmer)', Math.abs(A.dTmin + 5.14) < 0.02 && Math.abs(A.dTmax - 1.68) < 0.02, `${fx(A.dTmin, 2)} to ${fx(A.dTmax, 2)}`);
  ok('the centre keeps 67% of the sides\' swing and lags them 2.5 h (0.656 rad)', Math.abs(A.center.ratio - 0.670) < 0.002 && Math.abs(A.center.delay - 0.656) < 0.002,
    `${fx(A.center.ratio)} / ${fx(A.center.delay)} rad = ${fx(A.center.delayHours, 2)} h`);
  ok('flat-ground conduction with that delay would keep only 52%', Math.abs(A.need.flat.damp - 0.519) < 0.001, fx(A.need.flat.damp));
  const cm = [0.3e-6, 0.5e-6, 0.7e-6].map((k) => E.analyse(data, k).need);
  ok('solid needed for a 2.5 h conduction delay, kappa 0.3 to 0.7 mm²/s: 6 to 9 cm flat, 11 to 16 cm cylinder',
    Math.abs(cm[0].flat.cm - 5.96) < 0.05 && Math.abs(cm[2].flat.cm - 9.10) < 0.05 && Math.abs(cm[0].cylinder.cm - 10.66) < 0.05 && Math.abs(cm[2].cylinder.cm - 16.28) < 0.05,
    cm.map((n) => `${fx(n.flat.cm, 1)} / ${fx(n.cylinder.cm, 1)} cm`).join('; '));
  // Negative control: build a synthetic "centre" that IS a pure flat-conduction copy of the
  // sides 10 cm down; the same test must call it consistent (size = e^-delay).
  const per = E.peripheryCurve(data.ocko2017.curves);
  const pc = E.fourier(E.daySamples(per), 4);
  const fake = E.atDepth(pc, 0.10, 0.5e-6);
  const fakePts = []; for (let k = 0; k <= 480; k++) fakePts.push([24 * k / 480, E.evalSeries(fake, k * DAY / 480)]);
  const F = E.analyse({ ...data, ocko2017: { ...data.ocko2017, curves: { ...data.ocko2017.curves, center: fakePts } } }, 0.5e-6);
  ok('control: a centre made by pure conduction through 10 cm reads as size = e^-delay, and 10 cm comes back',
    Math.abs(F.center.ratio - Math.exp(-F.center.delay)) < 0.005 && Math.abs(F.need.flat.cm - 10) < 0.1,
    `size ${fx(F.center.ratio)}, e^-delay ${fx(Math.exp(-F.center.delay))}, recovered ${fx(F.need.flat.cm, 2)} cm`);
}

// ---------------------------------------------------------------------------
head('5. The nest under a metre of Namibia');
{
  const q = A.surfaceQuarters;
  ok('NASA POWER skin temperature, Omatjenne 2004: solstice quarters 28.6 and 17.4, a span of 11.2 degC',
    Math.abs(q.summer - 28.65) < 0.02 && Math.abs(q.winter - 17.40) < 0.02 && Math.abs(q.span - 11.25) < 0.02, `${fx(q.summer, 2)} / ${fx(q.winter, 2)} / ${fx(q.span, 2)}`);
  const pred = [];
  for (const k of [0.3e-6, 0.7e-6]) for (const x of [0.5, 1.0, 1.5, 2.0]) pred.push(q.span * E.analyse(data, k).nestYearAt(x));
  const lo = Math.min(...pred), hi = Math.max(...pred);
  ok('conduction alone predicts a nest quarterly span of 3.6 to 9.3 degC for 0.5 to 2 m and kappa 0.3 to 0.7', Math.abs(lo - 3.6) < 0.05 && Math.abs(hi - 9.3) < 0.05, `${fx(lo, 2)} to ${fx(hi, 2)}`);
  ok('Turner and Marais measured 9.4 (OM123) and 6.4 (OM126): one at the top edge of the band, one inside it', 9.4 > hi && 9.4 - hi < 0.2 && 6.4 > lo && 6.4 < hi);
  const day = [0.3e-6, 0.7e-6].map((k) => E.analyse(data, k).nestDailyAt(0.5));
  ok('the same ground at 0.5 m keeps 0.4% to 2.7% of the daily swing', Math.abs(day[0] - 0.0041) < 0.0002 && Math.abs(day[1] - 0.0272) < 0.0002, day.map((v) => (100 * v).toFixed(2) + '%').join(' to '));
  const air = data.namibiaAutumnDay;
  const sk = Math.max(...air.skinTemperature) - Math.min(...air.skinTemperature), at = Math.max(...air.airTemperature2m) - Math.min(...air.airTemperature2m);
  ok('the composite autumn day at the Ocko site: 36 days, skin swings 21.0 degC, air 14.7 degC', air.days === 36 && Math.abs(sk - 21.04) < 0.02 && Math.abs(at - 14.70) < 0.02, `skin ${fx(sk, 2)}, air ${fx(at, 2)}`);
}

// ---------------------------------------------------------------------------
head('6. The sources\' own arithmetic, redone');
{
  const C = (f) => (f - 32) * 5 / 9;
  ok('87 F is 30.6 C; 35 F is 1.7 C; 104 F is 40.0 C', Math.abs(C(87) - 30.56) < 0.01 && Math.abs(C(35) - 1.67) < 0.01 && Math.abs(C(104) - 40) < 1e-9);
  ok('the NYT\'s own Harare line, 88 F down to 58 F, is a 30 F (16.7 C) swing; its veld line is 69 F (38.3 C)', 88 - 58 === 30 && Math.abs(30 * 5 / 9 - 16.67) < 0.01 && 104 - 35 === 69 && Math.abs(69 * 5 / 9 - 38.33) < 0.01);
  ok('Harare-Kutsaga\'s absolute maximum, 35.0 C (DWD, 1941-1976), is 5 C short of 104 F', Math.abs(C(104) - 35.0 - 5) < 1e-9);
  ok('Arup 1997: 9.1 kWh/m² against 11 to 18.9 is 48% to 83%', Math.round(100 * 9.1 / 18.9) === 48 && Math.round(100 * 9.1 / 11) === 83);
  ok('Arup 1997: the ventilation tendered at Z$3M against about Z$25M for air conditioning, 12%', Math.round(100 * 3 / 25) === 12);
  ok('Turner and Marais: 31.0 - 14.5 = 16.5 and 31.5 - 21.0 = 10.5; quarterly 27.9 - 18.5 = 9.4 and 29.3 - 22.9 = 6.4',
    Math.abs(31.0 - 14.5 - 16.5) < 1e-9 && Math.abs(31.5 - 21.0 - 10.5) < 1e-9 && Math.abs(27.9 - 18.5 - 9.4) < 1e-9 && Math.abs(29.3 - 22.9 - 6.4) < 1e-9);
  // King et al. 2015 / Ocko et al. 2017 loop model, V = alpha dT g r^2 / (16 nu), cgs.
  const V = (dT) => (1 / 300) * dT * 981 * 9 / (16 * 0.16);
  ok('the papers\' closed-loop estimate: 3 C gives ~35 cm/s (King), 6 C gives ~70 cm/s (Ocko)', Math.abs(V(3) - 34.5) < 0.1 && Math.abs(V(6) - 69.0) < 0.1, `${fx(V(3), 1)} and ${fx(V(6), 1)} cm/s`);
  const dp = E.stackPressure(1, A.periphery.mean + A.dTmax, A.periphery.mean);
  ok('stack pressure of a 1 m column 1.7 C warmer than its neighbour: about 0.06 Pa', Math.abs(dp - 0.063) < 0.005, fx(dp, 4) + ' Pa');
}

// ---------------------------------------------------------------------------
head('7. The page says what was checked');
{
  let html = '';
  try { html = readFileSync(new URL('index.html', PAGE), 'utf8'); } catch {}
  const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&thinsp;/g, ' ').replace(/\s+/g, ' ');
  const must = ['09:23', '17:27', '2.5 hours', '67%', '52%', '1.7%', '0.10', '9.4', '6.4', '3.6 to 9.3', '48% to 83%', '16.5', '87', '104', '35.0'];
  const missing = must.filter((m) => !text.includes(m));
  ok('the page prints the numbers this file checks', html.length > 0 && missing.length === 0, missing.length ? 'missing: ' + missing.join(', ') : `${must.length} found`);
  ok('the page imports this engine and this data, not copies', /from\s+['"]\.\/engine\.mjs['"]/.test(html) && /data\.json/.test(html));
}

console.log(lines.join('\n'));
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail ? 1 : 0);
