// verify.mjs: checks for /strata/light-leans-toward-the-cold/.
// Run: node research/light-leans-toward-the-cold/verify.mjs
//
// Every number the page states about the physics is recomputed here from engine.mjs, and
// wherever a published value exists the engine is held against it. The published values
// are typed in below with their sources, so a reader can see exactly what was compared
// with what. Nothing here needs the network: the JPL Horizons ephemeris the solar model is
// checked against is committed alongside (horizons-1597.txt, fetched by fetch-horizons.mjs).

import { readFileSync } from 'node:fs';
import * as E from './engine.mjs';

const DEG = Math.PI / 180;
let pass = 0, fail = 0;
const lines = [];
function ok(name, cond, detail = '') {
  cond ? pass++ : fail++;
  lines.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  :  ' + detail : ''}`);
}
const rel = (a, b) => Math.abs(a - b) / Math.abs(b);

// ---------------------------------------------------------------------------
// 0. The page runs this exact engine.
{
  const a = readFileSync(new URL('./engine.mjs', import.meta.url), 'utf8');
  let b = null;
  try { b = readFileSync(new URL('../../public/strata/light-leans-toward-the-cold/engine.mjs', import.meta.url), 'utf8'); } catch {}
  ok('the page ships a byte-identical copy of this engine', a === b, b == null ? 'public copy not found' : `${a.length} bytes`);
}

// ---------------------------------------------------------------------------
// 1. The refractive index of air.
{
  const ns = E.refractivityStandardAir(0.55);
  ok('Ciddor (1996) eq. 1, standard dry air at 550 nm: n - 1 = 2.778e-4', Math.abs(ns - 2.778e-4) < 0.0005e-4, ns.toExponential(4));
  // van der Werf, Konnen & Lehn (2003), Appl. Opt. 42, 367: n - 1 = A p/T with
  // A = 7.8998e-5 (520 nm), 7.8686e-5 (580 nm), 7.8434e-5 (650 nm) K/hPa.
  const pub = [[0.52, 7.8998e-5], [0.58, 7.8686e-5], [0.65, 7.8434e-5]];
  let worst = 0;
  for (const [l, A] of pub) worst = Math.max(worst, rel(E.refractivityConstant(l), A));
  ok('c in n - 1 = c P/T matches van der Werf et al. (2003) at 520, 580, 650 nm to within 0.3%', worst < 0.003, `worst difference ${(worst * 100).toFixed(3)}%`);
  // Lehn (1979) appendix: n = 1 + eps*rho, eps = 226e-6 m^3/kg, rho = beta p / T, beta = 3.49e-3
  const lehn = 226e-6 * 3.49e-3 * 100; // K/hPa
  ok('and matches Lehn (1979), eps * beta = 7.89e-5 K/hPa', rel(E.refractivityConstant(0.55), lehn) < 0.005, `engine ${E.refractivityConstant(0.55).toExponential(4)}, Lehn ${lehn.toExponential(4)}`);
}

// ---------------------------------------------------------------------------
// 2. Ray curvature and the refraction coefficient.
{
  // Hirt, Guillaume, Wisbar, Burki & Sternberg (2010), J. Geophys. Res. 115, D21102:
  // k = 503 p/T^2 (0.0343 + dT/dz), and "p = 1013 hPa, T = 288.15 K and dT/dz = -0.0060 K/m
  // yield a local refraction coefficient of +0.17".
  const cR = E.refractivityConstant(0.55) * E.R_EARTH;
  ok('the engine\'s curvature law is Hirt et al.\'s: c * R_earth = 503', Math.abs(cR - 503) < 1, cR.toFixed(1));
  ok('and its pressure term g M / R = 0.0343 K/m', Math.abs(E.HYDRO - 0.0343) < 0.0002, E.HYDRO.toFixed(5));
  const atm = E.makeAtmosphere(E.makeProfile({ T0: 288.15, lapse: -0.0060 }), { P0: 1013 });
  const k = E.refractionCoefficient(atm, 0);
  ok('k = +0.17 for Hirt et al.\'s standard case', Math.abs(k - 0.17) < 0.005, k.toFixed(4));
  const std = E.presetAtmosphere('standard');
  const kStd = E.refractionCoefficient(std, 0);
  ok('the standard atmosphere (-6.5 K/km) at sea level gives k = 0.17, not the surveyor\'s 0.13', Math.abs(kStd - 0.17) < 0.005, kStd.toFixed(4));

  // The critical gradient, k = 1. Lehn (1979) Table 1: 0.112 K/m at 273 K; Wegener (1918)
  // 0.114; de Graaff Hunter (1913) 0.116 (both as quoted by A. T. Young).
  const g0 = E.criticalGradient(273.15, 1013.25);
  ok('critical inversion at 0 C, 1013 hPa: 0.112 K/m (Lehn 1979: 0.112)', Math.abs(g0 - 0.112) < 0.001, g0.toFixed(4) + ' K/m');
  const g15 = E.criticalGradient(288.15, 1013.25), gm30 = E.criticalGradient(243.15, 1013.25);
  ok('it depends on temperature: 0.129 K/m at 15 C, 0.082 K/m at -30 C', Math.abs(g15 - 0.129) < 0.001 && Math.abs(gm30 - 0.082) < 0.001, `${g15.toFixed(4)}, ${gm30.toFixed(4)}`);
  // Lehn (1979) Table 1: at a gradient of 0.112 K/m, k = 0.87 at 293 K and 1.37 at 233 K.
  const kAt = (T) => E.refractionCoefficient(E.makeAtmosphere(E.makeProfile({ T0: T, lapse: 0.112 }), { P0: 1013.25 }), 0);
  ok('Lehn\'s Table 1 at 0.112 K/m: k = 0.87 at 293 K, 1.37 at 233 K', Math.abs(kAt(293) - 0.87) < 0.01 && Math.abs(kAt(233) - 1.37) < 0.01, `${kAt(293).toFixed(3)}, ${kAt(233).toFixed(3)}`);

  // At k = 1 a horizontal ray stays at constant height: trace one for 200 km through air
  // held exactly at the critical gradient, and compare a standard-atmosphere ray.
  // tune a uniform gradient until k = 1 exactly at the ray's own height, 50 m
  const T = 273.15;
  let g = E.criticalGradient(T, 1013.25), crit;
  for (let it = 0; it < 30; it++) {
    crit = E.makeAtmosphere(E.makeProfile({ T0: T, lapse: g, tropo: 1e9 }), { P0: 1013.25 });
    g += (1 - E.refractionCoefficient(crit, 50)) * 0.1;
  }
  const t1 = E.trace(crit, 50, 0, { stopAt: 200000, dsMax: 500 });
  const t2 = E.trace(E.makeAtmosphere(E.makeProfile({ T0: T, lapse: -0.0065 }), { P0: 1013.25 }), 50, 0, { stopAt: 200000, dsMax: 500 });
  ok('at k = 1 a level ray holds its height for 200 km: the Earth looks flat', Math.abs(t1.z - 50) < 5, `moves ${(t1.z - 50).toFixed(2)} m at ${g.toFixed(4)} K/m (ordinary air: rises ${(t2.z - 50).toFixed(0)} m)`);
}

// ---------------------------------------------------------------------------
// 3. The integrator.
{
  let worst = 0;
  for (const name of Object.keys(E.PRESETS)) {
    const atm = E.presetAtmosphere(name);
    for (let a = -0.4; a <= 0.4; a += 0.05) {
      const t = E.trace(atm, 5, a * DEG, { maxDist: 60000, dsMax: 100 });
      worst = Math.max(worst, t.invDrift);
    }
  }
  ok('Bouguer\'s invariant n r cos(th) is conserved along every ray in every preset', worst < 1e-8, `worst drift ${worst.toExponential(1)}`);
  // quartering every step-size control changes where a ray meets a target by less than a
  // millimetre (road) or a few centimetres (sea); the fine run takes about four times the steps
  const road = E.presetAtmosphere('road'), sea = E.presetAtmosphere('sea');
  let dRoad = 0, dSea = 0;
  for (let a = -0.3; a <= 0.1; a += 0.02) {
    const x = E.trace(road, 1.6, a * DEG, { stopAt: 500, dsMax: 2 }), y = E.trace(road, 1.6, a * DEG, { stopAt: 500, dsMax: 0.5, acc: 0.005 });
    if (x.fate === 'reached' && y.fate === 'reached') dRoad = Math.max(dRoad, Math.abs(x.z - y.z));
  }
  for (let a = -0.1; a <= 0.15; a += 0.01) {
    const x = E.trace(sea, 10, a * DEG, { stopAt: 30000, dsMax: 100 }), y = E.trace(sea, 10, a * DEG, { stopAt: 30000, dsMax: 25, acc: 0.005 });
    if (x.fate === 'reached' && y.fate === 'reached') dSea = Math.max(dSea, Math.abs(x.z - y.z));
  }
  ok('the answer does not depend on the step size', dRoad < 1e-3 && dSea < 0.05 && dRoad > 0 && dSea > 0, `largest change: road ${dRoad.toExponential(1)} m, sea ${dSea.toExponential(1)} m (nonzero, so the two runs really differed)`);
}

// ---------------------------------------------------------------------------
// 4. Astronomical refraction: the whole engine against a standard almanac formula.
{
  // Bennett (1982), as Meeus eq. 16.4, for 10 C and 1010 hPa. Bennett states an accuracy of
  // about 0.07 arcmin; the model atmosphere here is not his, so the test allows 3.5%. The
  // residual is largest at 45 deg, where refraction depends only on the index at the ground
  // (the next check), so it lives in the refractivity value, not in the ray tracing.
  const atm = E.makeAtmosphere(E.makeProfile({ T0: 283.15, lapse: -0.0065 }), { P0: 1010 });
  const rows = [];
  let worst = 0;
  for (const h of [0, 0.5, 1, 2, 5, 10, 20, 45]) {
    const m = E.skyMap(atm, 0.001, [h * DEG], { dsMax: 500 })[0];
    const R = (h * DEG - m.trueElev) / DEG * 60, B = E.bennettRefraction(h);
    rows.push(`${h}° ${R.toFixed(2)}'/${B.toFixed(2)}'`);
    worst = Math.max(worst, rel(R, B));
  }
  ok('traced refraction from horizon to 45 deg agrees with Bennett\'s formula within 3.5%', worst < 0.035, rows.join(', '));
  const n0 = atm.nm1(0), R45 = E.skyMap(atm, 0.001, [45 * DEG], { dsMax: 200 })[0];
  const R45traced = 45 * DEG - R45.trueElev;
  ok('at 45 deg it equals the local-index limit (n0 - 1) tan z, as it must', rel(R45traced, n0) < 0.01, `${(R45traced / DEG * 3600).toFixed(1)}" vs ${(n0 / DEG * 3600).toFixed(1)}"`);
}

// ---------------------------------------------------------------------------
// 5. The hot road.
{
  // A ray that starts at eye height descending at angle th turns back before the road if
  // n(eye) cos(th) > n(road): th_c = arccos(n_road / n_eye), about sqrt(2 dn).
  const atm = E.presetAtmosphere('road');
  const eye = 1.6;
  const thc = Math.acos(atm.n(0) / atm.n(eye));
  // find the traced boundary between rays that turn and rays that hit the road
  let lo = 0, hi = 1 * DEG;
  for (let i = 0; i < 50; i++) {
    const m = (lo + hi) / 2;
    const t = E.trace(atm, eye, -m, { maxDist: 3000, dsMax: 1, zEsc: 50 });
    if (t.fate === 'ground') hi = m; else lo = m;
  }
  ok('the deepest mirage ray: traced boundary matches arccos(n_road / n_eye)', rel(lo, thc) < 0.02, `traced ${(lo / DEG * 60).toFixed(2)}', closed form ${(thc / DEG * 60).toFixed(2)}'`);
  // the preset shows the car twice, the lower image inverted
  const al = []; for (let i = 0; i < 400; i++) al.push((0.1 - 0.72 * (i + 0.5) / 400) * DEG);
  const rows = E.transfer(atm, eye, 500, al, { beyond: 1.0001 });
  let n = 0, inv = 0;
  for (let k = 1; k < rows.length; k++) {
    const a = rows[k - 1].hAtD, b = rows[k].hAtD;
    if (a != null && b != null && (a - 0.56) * (b - 0.56) < 0) { n++; if (b > a) inv++; }
  }
  ok('hot-road preset: the car\'s headlamps are seen twice, once upside down', n === 2 && inv === 1, `${n} images, ${inv} inverted`);
}

// ---------------------------------------------------------------------------
// 6. The Sun in 1597.
const HUT = { lat: 76 + 15.4 / 60, lon: 68 + 18.6 / 60 }; // van der Werf, Konnen, Lehn et al. (2003)
{
  // Meeus, Astronomical Algorithms, example 25.a: 1992 Oct 13.0 TD, apparent
  // RA 198.38083 deg, declination -7.78507 deg.
  const p = E.sunPosition(2448908.5);
  ok('solar model reproduces Meeus example 25.a', Math.abs(p.dec / DEG + 7.78507) < 0.0005 && Math.abs(((p.ra / DEG) + 360) % 360 - 198.38083) < 0.0005, `dec ${(p.dec / DEG).toFixed(5)}, RA ${(((p.ra / DEG) + 360) % 360).toFixed(5)}`);

  // against JPL Horizons, airless apparent elevation, every 10 minutes for 24 days
  const txt = readFileSync(new URL('./horizons-1597.txt', import.meta.url), 'utf8');
  const body = txt.slice(txt.indexOf('$$SOE') + 5, txt.indexOf('$$EOE'));
  const MON = { Jan: 1, Feb: 2 };
  let worst = 0, n = 0;
  for (const line of body.trim().split('\n')) {
    const m = line.match(/^\s*(\d{4})-(\w{3})-(\d{2}) (\d{2}):(\d{2})\s+\S*\s+([-\d.]+)\s+([-\d.]+)/);
    if (!m) continue;
    const jd = E.julianDayGregorian(+m[1], MON[m[2]], +m[3]) + (+m[4] + +m[5] / 60) / 24;
    const el = +m[7];
    worst = Math.max(worst, Math.abs(E.sunAltitude(jd, HUT.lat, HUT.lon) / DEG - el));
    n++;
  }
  ok('solar model agrees with JPL Horizons at the hut, 1597 Jan 20 to Feb 12', n > 3000 && worst < 0.02, `${n} epochs, worst ${worst.toFixed(4)} deg`);

  const d24 = E.sunHighest(E.julianDayGregorian(1597, 1, 24), HUT.lat, HUT.lon).alt / DEG;
  const d27 = E.sunHighest(E.julianDayGregorian(1597, 1, 27), HUT.lat, HUT.lon).alt / DEG;
  ok('24 Jan 1597: the Sun\'s centre was 5 deg 26 min below the horizon (van der Werf et al. 2003)', Math.abs(d24 + (5 + 26 / 60)) < 0.03, `${d24.toFixed(3)} deg`);
  ok('27 Jan 1597: 4 deg 41 min below (same source)', Math.abs(d27 + (4 + 41 / 60)) < 0.03, `${d27.toFixed(3)} deg`);
  const jul = E.sunHighest(E.julianDayJulian(1597, 1, 24), HUT.lat, HUT.lon).alt / DEG;
  ok('had the dates been Julian (24 Jan O.S. = 3 Feb N.S.) the depression would be far smaller', jul > -3.2 && jul < -2.5, `${jul.toFixed(2)} deg`);
}

// ---------------------------------------------------------------------------
// 7. What ordinary air allows, and what Lehn's thermocline allows.
{
  const SUN_R = 16.25 / 60 * DEG;
  const ordinary = E.makeAtmosphere(E.makeProfile({ T0: 243.15, lapse: -0.0065 }), { P0: 1013.25 });
  const al = []; for (let i = 0; i < 1200; i++) al.push((0.6 - 0.8 * (i + 0.5) / 1200) * DEG);
  const map0 = E.skyMap(ordinary, 5, al, { maxDist: 3e6, dsMax: 1500 });
  const lowest0 = Math.min(...map0.filter((m) => m.trueElev != null).map((m) => m.trueElev));
  // first date on which the upper limb clears the lowest line of sight ordinary air offers
  let first = null;
  for (let d = 20; d <= 50 && first == null; d++) {
    const h = E.sunHighest(E.julianDayGregorian(1597, 1, 1) + d, HUT.lat, HUT.lon).alt;
    if (h + SUN_R >= lowest0) first = d + 1;
  }
  const firstLabel = first > 31 ? `${first - 31} February` : `${first} January`;
  ok('in ordinary arctic air the lowest sight line reaches 0.8 deg below the horizon', Math.abs(lowest0 / DEG + 0.8) < 0.1, `${(lowest0 / DEG).toFixed(3)} deg`);
  ok('so the Sun\'s upper limb first shows within a day of 8 February, the date Barentsz expected', Math.abs(first - 39) <= 1, firstLabel);

  // Lehn (1979): "an inversion of magnitude 6 C with maximum temperature gradient of
  // 0.2 C/m is quite adequate"; "the most difficult of the conditions to be met is the vast
  // uniform expanse". Here: +6 K over a layer at 30 m (steepest 0.2 K/m), ending at L km.
  const thermo = E.makeAtmosphere(E.makeProfile({ T0: 243.15, lapse: -0.0065, inv: { dT: 6, z: 30, w: 7.5 } }), { P0: 1013.25 });
  let steep = 0; for (let z = 0; z < 100; z += 0.05) steep = Math.max(steep, thermo.dT(z));
  ok('the thermocline used is Lehn\'s: +6 K, steepest gradient 0.2 K/m', Math.abs(steep - 0.2) < 0.01, `${steep.toFixed(3)} K/m`);
  const h24 = E.sunHighest(E.julianDayGregorian(1597, 1, 24), HUT.lat, HUT.lon).alt;
  const seen = (L) => {
    const map = E.skyMap(thermo, 5, al, { maxDist: 3e6, dsMax: 1500, mark: 30, edge: L * 1000, atmFar: ordinary });
    const hits = map.filter((m) => m.trueElev != null && Math.abs(m.trueElev - h24) < SUN_R);
    return { hits, map };
  };
  const vis = [];
  for (let L = 300; L <= 800; L += 20) if (seen(L).hits.length) vis.push(L);
  const lo = Math.min(...vis), hi = Math.max(...vis);
  ok('on 24 January that layer shows the Sun only if it runs about 500 to 600 km', vis.length > 0 && lo >= 460 && hi <= 640, `visible for extents ${lo} to ${hi} km`);
  const at540 = seen(540);
  const band = at540.hits.map((m) => m.alpha);
  const span = (Math.max(...band) - Math.min(...band)) / DEG * 60;
  const under = Math.max(...at540.hits.map((m) => m.lastBelow)) / 1000;
  ok('at 540 km the Sun is a strip a few arcminutes tall (a whole Sun is 32.5)', span > 2 && span < 12, `${span.toFixed(1)} arcmin tall, light ran up to ${under.toFixed(0)} km under the layer`);
  // Lehn's window: the strip is bounded above and below by rays that end on the ice
  const idx = at540.map.findIndex((m) => at540.hits.includes(m));
  const lastIdx = at540.map.length - 1 - [...at540.map].reverse().findIndex((m) => at540.hits.includes(m));
  const aboveDark = at540.map.slice(Math.max(0, idx - 30), idx).some((m) => m.fate === 'ground');
  const belowDark = at540.map.slice(lastIdx + 1, lastIdx + 31).some((m) => m.fate === 'ground');
  ok('and it sits in a window with dark bands above and below it, Lehn\'s "narrow strip"', aboveDark && belowDark, `dark above: ${aboveDark}, dark below: ${belowDark}`);
}

console.log(lines.join('\n'));
console.log(`\n${pass}/${pass + fail} checks pass`);
process.exit(fail ? 1 : 0);
