// verify-why-does-dew-form.mjs: checks /strata/why-does-dew-form/ ("The Cold Comes First") against the
// engine, pipeline and data the page actually serves, against independent formulas written here, against
// NOAA's own files, and against the text of the 1814 book it quotes.
//
//   node verify-why-does-dew-form.mjs          # fetches the 16 NOAA files behind the 8 chosen nights (~4 MB)
//   node verify-why-does-dew-form.mjs --full   # fetches all 734 files (~190 MB) and rebuilds the whole year
//   node verify-why-does-dew-form.mjs --offline  # physics, internal consistency and page text only
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it downloads
// the page's engine.mjs, pipeline/*.mjs, data/*.json and index.html from https://artwaste.land into
// ./why-does-dew-form-files/ (the bytes your browser runs) and imports them from there.
// NOAA files are cached in ./.dew-cache. Exit 0 = every check passed.

import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'why-does-dew-form';
const FULL = process.argv.includes('--full'), OFFLINE = process.argv.includes('--offline');
const FILES = ['engine.mjs', 'pipeline/lib.mjs', 'pipeline/analyze.mjs', 'pipeline/fetch.mjs', 'pipeline/build.mjs', 'data/findings.json', 'data/nights.json', 'data/showcase.json', 'index.html'];
let dir = join(here, 'public/strata', slug);
if (!existsSync(join(dir, 'engine.mjs'))) {
  dir = resolve(`${slug}-files`);
  for (const f of FILES) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    mkdirSync(dirname(join(dir, f)), { recursive: true }); writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const imp = (f) => import(pathToFileURL(join(dir, f)).href);
const E = await imp('engine.mjs'), L = await imp('pipeline/lib.mjs'), A = await imp('pipeline/analyze.mjs'), F = await imp('pipeline/fetch.mjs'), B = await imp('pipeline/build.mjs');
const J = (f) => JSON.parse(readFileSync(join(dir, f), 'utf8'));
const findings = J('data/findings.json'), nights = J('data/nights.json'), showcase = J('data/showcase.json');
const html = readFileSync(join(dir, 'index.html'), 'utf8');

let fails = 0, passes = 0;
const ok = (c, msg) => { if (c) passes++; else fails++; console.log((c ? 'PASS  ' : 'FAIL  ') + msg); };
const near = (a, b, tol) => Math.abs(a - b) <= tol;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const q = (a, p) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(p * (s.length - 1))]; };

// ── 1. physics, against independent formulas ─────────────────────────────────────────────────────
{
  // Hyland and Wexler (1983) saturation vapour pressure, a different functional form, in Pa
  const hwW = (t) => { const T = t + 273.15; return Math.exp(-5.8002206e3 / T + 1.3914993 - 4.8640239e-2 * T + 4.1764768e-5 * T * T - 1.4452093e-8 * T ** 3 + 6.5459673 * Math.log(T)) / 100; };
  const hwI = (t) => { const T = t + 273.15; return Math.exp(-5.6745359e3 / T + 6.3925247 - 9.677843e-3 * T + 6.2215701e-7 * T * T + 2.0747825e-9 * T ** 3 - 9.484024e-13 * T ** 4 + 4.1635019 * Math.log(T)) / 100; };
  let wW = 0, wI = 0;
  for (let t = -40; t <= 40; t += 0.5) wW = Math.max(wW, Math.abs(E.esWater(t) / hwW(t) - 1));
  for (let t = -50; t <= 0; t += 0.5) wI = Math.max(wI, Math.abs(E.esIce(t) / hwI(t) - 1));
  ok(wW < 0.005, `saturation over water (Magnus, Alduchov and Eskridge) within ${(100 * wW).toFixed(2)}% of Hyland and Wexler from -40 to 40 C`);
  ok(wI < 0.005, `saturation over ice within ${(100 * wI).toFixed(2)}% of Hyland and Wexler from -50 to 0 C`);
  let wD = 0; for (const t of [-20, -5, 0, 7, 15, 25, 35]) for (const rh of [20, 50, 80, 99]) wD = Math.max(wD, Math.abs(E.esWater(L.dewPoint(t, rh)) - rh / 100 * E.esWater(t)));
  ok(wD < 1e-9, `dew point is the exact inverse of the vapour-pressure curve (worst ${wD.toExponential(1)} hPa)`);
  ok(near(L.radTemp(5.670374419e-8 * 273.15 ** 4), 0, 1e-9) && near(L.radTemp(300), Math.sqrt(Math.sqrt(300 / 5.670374419e-8)) - 273.15, 1e-9), `radiating temperature: 300 W/m2 is ${L.radTemp(300).toFixed(2)} C; a black body at 0 C returns 0 C`);
  let wS = 0; for (const ts of [-30, -5, 5, 20]) for (const dw of [200, 300, 400]) for (const eps of [0.95, 0.98, 1]) { const uw = eps * E.SIGMA * (ts + 273.15) ** 4 + (1 - eps) * dw; wS = Math.max(wS, Math.abs(L.surfTemp(uw, dw, eps) - ts)); }
  ok(wS < 1e-9, `field temperature recovered from a synthetic downward pyrgeometer reading, reflection included (worst ${wS.toExponential(1)} C)`);
  // the handkerchief's view factor, by brute quadrature of cos^2 / (pi r^2) over the square
  const a = 24, h = 6, n = 1200; let s = 0; const d = a / n;
  for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) { const x = -a / 2 + (i + 0.5) * d, y = -a / 2 + (j + 0.5) * d, r2 = x * x + y * y + h * h; s += (h * h) / (Math.PI * r2 * r2) * d * d; }
  ok(near(E.WELLS_COVER, s, 1e-4) && near(E.WELLS_COVER, 0.831, 0.001), `Wells's handkerchief (2 ft square, 6 in up) covers ${E.WELLS_COVER.toFixed(4)} of the grass's sky; quadrature ${s.toFixed(4)}`);
  ok(near(E.viewToSquare(1e6, 1), 1, 1e-5), 'an infinite sheet covers the whole sky (view factor 1)');
  // balance(): the returned temperature zeroes the energy budget, recomputed here term by term
  const inp = { dw: 300, ta: 12, rh: 85, u10: 2, p: 990 };
  for (const view of [1, 0.5, 0.1]) {
    const b = E.balance(inp, { view }), T = b.ts + 273.15, h2 = 5.7 + 3.8 * (2 * Math.log(0.5 / 0.03) / Math.log(10 / 0.03));
    const net = 0.98 * (view * 300 + (1 - view) * E.SIGMA * (285.15) ** 4) - 0.98 * E.SIGMA * T ** 4 + h2 * (12 - b.ts) + (b.ts >= 0 ? 2.45e6 : 2.834e6) * b.cond;
    ok(Math.abs(net) < 1e-6, `view ${view}: surface ${b.ts.toFixed(3)} C, budget closes to ${net.toExponential(1)} W/m2, condensing ${(b.cond * 3600).toFixed(4)} mm/h`);
  }
  ok(near(E.balance({ dw: 250, ta: 10, rh: 60, u10: 3 }, { view: 0 }).ts, 10, 1e-6), 'a surface that sees no sky, in unsaturated air, sits exactly at the air temperature');
  const clear = { dw: 280, ta: 15, rh: 70, u10: 1 };
  const byWind = [0, 1, 3, 8].map(u => E.balance({ ...clear, u10: u }).ts), byView = [1, 0.5, 0.1].map(v => E.balance(clear, { view: v }).ts);
  ok(byWind.every((v, i) => !i || v > byWind[i - 1]) && byView.every((v, i) => !i || v > byView[i - 1]), `more wind or less sky always warms the surface (${byWind.map(v => v.toFixed(2)).join(' < ')}; ${byView.map(v => v.toFixed(2)).join(' < ')})`);
  const sh = E.balanceSheltered(inp);
  const h3 = 5.7 + 3.8 * (2 * Math.log(0.5 / 0.03) / Math.log(10 / 0.03)), Em = (t) => 0.98 * E.SIGMA * (t + 273.15) ** 4, c = E.WELLS_COVER;
  const lat = (t) => { const es = t >= 0 ? E.esWater(t) : E.esIce(t), qq = (e) => 0.622 * e / (990 - 0.378 * e); return (t >= 0 ? 2.45e6 : 2.834e6) * Math.max(0, h3 / 1004 * (qq(0.85 * E.esWater(12)) - qq(es))); };
  const rC = 0.98 * 300 - Em(sh.cloth) + Em(sh.ts) - Em(sh.cloth) + 2 * h3 * (12 - sh.cloth) + lat(sh.cloth);
  const rG = 0.98 * (1 - c) * 300 + c * Em(sh.cloth) - Em(sh.ts) + h3 * (12 - sh.ts) + lat(sh.ts);
  ok(Math.abs(rC) < 1e-3 && Math.abs(rG) < 1e-3 && sh.ts > E.balance(inp).ts, `handkerchief: cloth ${sh.cloth.toFixed(2)} C and grass ${sh.ts.toFixed(2)} C both balance (residuals ${rC.toExponential(1)}, ${rG.toExponential(1)} W/m2); the sheltered grass is warmer than open grass`);
}

// ── 2. the data files agree with themselves ──────────────────────────────────────────────────────
for (const st of ['bon', 'dra']) {
  const N = nights[st], S = findings.stations[st];
  ok(N.length === S.nights && N.every(n => n.date.startsWith('2025')), `${st}: ${N.length} nights, all of them evenings in 2025`);
  ok(S.condNightsAny === N.filter(n => n.condMin > 0).length && S.condNightsHour === N.filter(n => n.condMin >= 60).length, `${st}: ${S.condNightsAny} nights with any possible deposition, ${S.condNightsHour} with an hour or more (recounted from nights.json)`);
  ok(S.robustness['eps0.98_m0'].anyMin === S.condNightsAny && S.robustness['eps0.98_m0'].hourPlus === S.condNightsHour, `${st}: the robustness grid's central cell is the headline`);
  const cl = N.filter(n => n.epsSky < 0.8);
  ok(cl.length === S.clearNights && q(cl.map(n => n.skyMinusAir), 0.5) === S.clearSkyMinusAirMedian, `${st}: ${cl.length} clear nights, sky ${S.clearSkyMinusAirMedian} C from the air at the median`);
  ok(S.thirds.cells.reduce((s, c) => s + c.nights, 0) === N.length, `${st}: the nine sky-by-wind cells hold every night between them`);
  ok(Math.max(...N.map(n => n.ceilingMm)) === S.ceilingMax, `${st}: the dew ceiling never exceeds ${S.ceilingMax} mm in 2025`);
  const hp = Object.values(S.robustness).map(v => v.hourPlus);
  ok(true, `${st}: nights with an hour or more across emissivity 0.95/0.98/0.99 and field shifts of -0.5/0/+0.5 C: ${Math.min(...hp)} to ${Math.max(...hp)}`);
}
ok(findings.stations.bon.condNightsHour > 10 * Math.max(...Object.values(findings.stations.dra.robustness).map(v => v.hourPlus)), 'in every one of the nine variants Bondville has more than ten times as many nights with an hour of possible deposition as Desert Rock');

// ── 3. the page's words agree with the data ──────────────────────────────────────────────────────
{
  const b = findings.stations.bon, d = findings.stations.dra, P = b.precedingCold, cell = (T, s, w) => T.cells.find(c => c.sky === s && c.wind === w);
  const cc = cell(b.thirds, 'clearest third', 'calmest third'), ww = cell(b.thirds, 'cloudiest third', 'windiest third');
  const c05 = cell(b.thirdsMargin05, 'cloudiest third', 'calmest third'), w05 = cell(b.thirdsMargin05, 'cloudiest third', 'windiest third'), c0 = cell(b.thirds, 'cloudiest third', 'calmest third');
  const hp = (s) => Object.values(findings.stations[s].robustness).map(v => v.hourPlus);
  const dew = showcase.find(n => n.id === 'dew').summary, dry = showcase.find(n => n.id === 'dry').summary, ev = b.cloudEvents, evWarm = ev.find(e => e.air > 5);
  const sky = showcase.filter(n => n.summary.epsSky < 0.85).map(n => -n.summary.skyMinusAir);
  const five = b.coldestFive, words = ['none', 'One', 'Two', 'Three', 'Four', 'Five'];
  const claims = [
    [`${b.condNightsAny}</b><span>nights of ${b.nights} at Bondville`, 'Bondville headline'],
    [`(${b.condNightsHour} for an hour or more)`, 'Bondville, an hour or more'],
    [`${d.condNightsAny}</b><span>nights of ${d.nights} at Desert Rock (${d.condNightsHour} for an hour or more)`, 'Desert Rock headline'],
    [`${b.clearSkyMinusAirMedian.toFixed(1).replace('-', '−')} °C</b><span>Bondville's clear-sky nights`, 'Bondville clear sky'], [`(median of ${b.clearNights} nights)`, 'Bondville clear count'],
    [`${d.clearSkyMinusAirMedian.toFixed(1).replace('-', '−')} °C</b><span>Desert Rock's clear-sky nights (median of ${d.clearNights})`, 'Desert Rock clear sky'],
    [`a median ${d.dewDepressionMedian} °C below its temperature (Bondville's: ${b.dewDepressionMedian} °C)`, 'dew-point depressions'],
    [`sits ${Math.round(Math.min(...sky))} to ${Math.round(Math.max(...sky))} °C below the orange air`, 'clear-night sky range across the chosen nights'],
    [`reached the dew point ${dew.firstDepMin} minutes later`, 'dew night timing'],
    [`${(-dry.surfMinusAir).toFixed(1)} °C on average and ${(-dry.minSurfMinusAir).toFixed(1)} °C at the coldest minute`, 'the coldest-grass night'],
    [`${words[five.filter(n => n.condMin === 0).length]} of the five nights of 2025`, 'coldest five with no deposition'],
    [`the coldest of all had a dew point ${five[0].dewDepression} °C below the air`, 'coldest night dew depression'],
    [`ran ${(-cc.meanSurfMinusAir).toFixed(1)} °C below the air on the clearest, calmest third of nights and ${(-ww.meanSurfMinusAir).toFixed(1)} °C on the cloudiest, windiest third, and ${cc.condNights} of ${cc.nights} clear, calm nights`, 'clear-calm vs cloudy-windy'],
    [`falls from ${c0.condNights} nights to ${c05.condNights}, and the cloudy-windy one from ${ww.condNights} to ${w05.condNights}`, 'sensor-doubt shifts'],
    [`On ${P.nights} nights of 2025 at Bondville`, 'preceding-cold nights'], [`On ${P.coldFirst} of them the cold came first`, 'cold first'],
    [`${Math.floor(P.medianDepMin / 60)} hours ${P.medianDepMin % 60} minutes later. On ${P.depFirst} nights the order was reversed`, 'median lag, reversals'],
    [`median of <b>${b.ceilingMedianOnCondNights.toFixed(2)} mm</b>`, 'ceiling median'], [`never above <b>${Math.ceil(b.ceilingMax * 10) / 10} mm</b>`, 'ceiling max'],
    [`was ${ev[0].surfaceWarmedC} °C, on a January evening`, 'largest cloud warming'], [`was ${evWarm.surfaceWarmedC} °C, at ${evWarm.local.slice(11)} on 24 August`, 'largest cloud warming with the air above 5 C'],
    [`it runs <b>${(-b.validation['1'].odd.bias).toFixed(1)} °C colder</b>`, 'model bias'], [`${b.validation['1'].odd.rmse} to ${b.validation['1'].even.rmse} °C (odd and even days)`, 'model RMS'],
    [`${(-b.validation['1'].odd.bias).toFixed(2)} °C colder on average at Bondville (RMS ${b.validation['1'].odd.rmse} °C on odd days, ${b.validation['1'].even.rmse} °C on even), and ${(-d.validation['1'].odd.bias).toFixed(1)} °C colder at Desert Rock`, 'model, the check'],
    [`(${(-d.validation['1'].byWind[0].bias).toFixed(1)} °C below 2 m/s, ${(-d.validation['1'].byWind[3].bias).toFixed(1)} °C above 6 m/s)`, 'desert model error by wind'],
    [`does worse, ${(-b.validationWatmuff['1'].odd.bias).toFixed(1)} °C colder at Bondville`, 'the alternative coefficient'],
    [`range from ${Math.min(...hp('bon'))} to ${Math.max(...hp('bon'))}, Desert Rock's from ${Math.min(...hp('dra'))} to ${Math.max(...hp('dra'))}`, 'robustness ranges'],
    [`field ran 4.6 °C below its (higher, 10 m) air on the average clear, calm night`, 'clear-calm deficit, repeated'],
  ];
  const text = html.replace(/\s+/g, ' ');
  for (const [s, what] of claims) ok(text.includes(s), `page text matches the data: ${what}: "${s.replace(/<[^>]+>/g, '')}"`);
  ok(near(-cc.meanSurfMinusAir, 4.6, 0.05), 'the 4.6 C clear-calm figure is the table cell');
  ok(text.includes(`over <span class="mono" id="coverV"></span>`) && text.includes('seeing it over 0.83 of its sky'), 'the handkerchief cover is written once from the engine and once as 0.83');
  // Wells's arithmetic on the page
  const f2c = (f) => f * 5 / 9;
  ok(text.includes(`11 °F (${f2c(11).toFixed(1)} °C)`) && text.includes(`14 °F (${f2c(14).toFixed(1)} °C)`) && text.includes(`3 °F (${f2c(3).toFixed(1)} °C)`) && text.includes(`<td>${Math.round(800 / 11)}%</td>`) && text.includes(`<td>${Math.round(1100 / 14)}%</td>`), "Wells's handkerchief nights converted and their share of cold removed (8 of 11, 11 of 14)");
  ok(text.includes(`Seven Fahrenheit degrees in twenty minutes is ${f2c(7).toFixed(1)} °C`) && text.includes(`In Celsius that is ${f2c(7).toFixed(1)} to ${f2c(12).toFixed(1)} °C`), "Wells's Fahrenheit differences converted (7 F = 3.9 C; 7 to 12 F = 3.9 to 6.7 C)");
}

// ── 4. every quotation, against the Internet Archive's text of the 1814 book ─────────────────────
const QUOTES = [
  ['the same degree of cold, in the precipitating body, may be attended with much, with little, or with no dew, according to the existing state of the air, in regard to moisture', 59],
  ['very little dew appeared upon the two nights of the greatest cold I have ever observed on the surface of the earth, relatively to the temperature of the air, both of which nights having occurred after a long tract of dry weather', 60],
  ['I have frequently found a small quantity of dew on grass, both on windy nights, if the sky was clear, or nearly so, and on cloudy nights, if there was no wind; but none has ever been seen by me on nights, that were both cloudy and windy', 5],
  ['but I soon saw reason, after my regular course of experiments was begun, to doubt its truth, as I found that bodies would sometimes become colder than the air, without being dewed', 54],
  ['that dew is the production of a preceding cold in the substances, upon which it appears', 54],
  ['The formation of dew, indeed, not only does not produce cold, but, like every other precipitation of water from the atmosphere, produces heat.', 59],
  ['But after the dew had become very abundant, the difference of those temperatures never exceeded 4° and was frequently only 3°', 60],
  ['very frequently found the grass, at the ordinary place of my observations, 7, 8, or 9 degrees colder than the air. Several times it was 10° and 11° colder than the air, and once 12°', 28],
  ['only 2 grains, but that, which had been exposed to the sky, 16 grains', 15],
  ['a fine cambrick handkerchief, rendered by long wear still thinner than it had been originally, and having here and there a slight rent.', 121],
  ['when fully exposed grass was 11° colder than the air, the latter was 3° warmer than the sheltered grass', 122],
  ["During a fourth night, the temperature of the grass at half past 9 o'clock was 32°. In 20 minutes afterwards, it was found to be 39°, the sky having in the mean time become cloudy. At the end of 20 minutes more, the sky being clear, the temperature of the grass was again 32°.", 32],
];
const DARWIN = 'In this paper he distinctly recognises the principle of natural selection, and this is the first recognition which has been indicated; but he applies it only to the races of man, and to certain characters alone.';
const norm = (s) => s.replace(/[‘’]/g, "'").replace(/-\s*\n\s*/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '');
const pageText = norm(html.replace(/<[^>]+>/g, ' ').replace(/&#39;/g, "'"));
// smallest edit distance of the quote against any substring of the text (Sellers' algorithm)
function bestMatch(pat, txt) { let prev = new Uint16Array(pat.length + 1).map((_, i) => i), cur = new Uint16Array(pat.length + 1), best = 1e9;
  for (let j = 1; j <= txt.length; j++) { cur[0] = 0; const c = txt.charCodeAt(j - 1);
    for (let i = 1; i <= pat.length; i++) cur[i] = Math.min(prev[i] + 1, cur[i - 1] + 1, prev[i - 1] + (pat.charCodeAt(i - 1) === c ? 0 : 1));
    if (cur[pat.length] < best) best = cur[pat.length]; [prev, cur] = [cur, prev]; }
  return best; }
if (!OFFLINE) {
  const ocr = norm(await (await fetch('https://archive.org/download/b21299742/b21299742_djvu.txt')).text());
  for (const [qt, pg] of QUOTES) {
    const p = norm(qt), onPage = pageText.includes(p), dist = bestMatch(p, ocr);
    ok(onPage && dist <= Math.max(3, Math.round(0.03 * p.length)), `Wells p. ${pg}: quoted on the page, and found in the book's OCR text with ${dist} character difference(s) in ${p.length} (OCR noise; the page image is https://archive.org/details/b21299742/page/n${pg + 9}/)`);
  }
  const origin = norm(await (await fetch('https://www.gutenberg.org/cache/epub/2009/pg2009.txt')).text());
  ok(pageText.includes(norm(DARWIN)) && origin.includes(norm(DARWIN)), "Darwin's sentence on Wells appears verbatim in Project Gutenberg #2009 (the sixth edition of the Origin)");
} else ok(true, 'quotations: skipped (--offline)');

// ── 5. the chosen nights, rebuilt from NOAA's files ──────────────────────────────────────────────
if (!OFFLINE && !FULL) {
  const cache = resolve('.dew-cache');
  for (const n of showcase) {
    const t0 = new Date(n.startUTC + 'Z'), days = [0, 1].map(k => new Date(t0.getTime() + k * 864e5));
    const texts = [];
    for (const d of days) { const y = d.getUTCFullYear(), j = Math.round((Date.UTC(y, d.getUTCMonth(), d.getUTCDate()) - Date.UTC(y, 0, 1)) / 864e5) + 1;
      const [p] = await F.ensure(n.station, y, [j], cache); texts.push(readFileSync(p, 'utf8')); }
    const { rows } = A.loadRows(texts);
    const night = A.splitNights(rows, n.station).find(x => x.start === Date.parse(n.startUTC + 'Z') / 60000);
    const s = A.summarise(night), tr = A.trace(night), { event, ...sum } = n.summary;
    ok(same(s, sum) && same(tr, n.trace), `${n.id}: ${n.station} night of ${s.date} rebuilt from NOAA's two daily files: summary and ${tr.m.length}-point trace identical`);
    ok(near(B.modelNight(tr), n.modelDewMm, 1e-9) && same(B.handkerchief(tr), n.handkerchief), `${n.id}: model dew ${n.modelDewMm} mm and handkerchief deficits reproduce`);
    if (event) ok(A.cloudEvents(rows, n.station).some(e => same(e, event)), `${n.id}: the cloud event at ${event.local} (field +${event.surfaceWarmedC} C, sky IR +${event.skyIRRoseW} W/m2) is found again in the raw minutes`);
  }
}
if (FULL) {
  const out = await B.build({ cache: resolve('.dew-cache'), log: () => {} });
  for (const [f, txt] of Object.entries(B.serialise(out))) ok(txt === readFileSync(join(dir, 'data', f), 'utf8'), `--full: data/${f} rebuilt byte for byte from all 734 NOAA files`);
}

console.log(`\n${passes} passed, ${fails} failed`);
process.exit(fails ? 1 : 0);
