// engine.mjs: a ray tracer for light in a layered atmosphere over a round Earth.
//
// Used verbatim by the page (public/strata/light-leans-toward-the-cold/engine.mjs is a
// byte-identical copy, and verify.mjs fails if the two ever differ) and by the verifier.
// No imports, no dependencies: the whole model is in this file.
//
// THE MODEL, and every assumption in it:
//   * The atmosphere is spherically layered: temperature depends on height only.
//     (A real mirage sits over a road or a sea that is not uniform; this is the
//     simplification every textbook mirage model makes, and it is named on the page.)
//   * Pressure follows from temperature by hydrostatic balance, dP/dz = -P g M / (R T),
//     integrated numerically from a surface pressure.
//   * The refractive index of air is n = 1 + c * P / T, with c fixed by the refractivity
//     of standard dry air at one wavelength (Ciddor 1996, eq. 1, which is the Birch and
//     Downs dispersion formula). Humidity is ignored. Scaling (n - 1) with density P/T is
//     the ideal-gas form of the Lorentz-Lorenz relation; at these values of n the error is
//     far below anything a mirage depends on.
//   * Rays obey the exact ray equation for a spherically layered medium, in polar form:
//        dr/ds = sin(th),  dphi/ds = cos(th)/r,  dth/ds = cos(th) * (1/r + n'(r)/n)
//     where th is the ray's elevation above the local horizontal. Its first integral,
//     n * r * cos(th) = constant (Bouguer's rule, Snell's law for spheres), is carried as a
//     running check on the integrator.

export const R_EARTH = 6371000;          // m, mean radius
export const G0 = 9.80665;               // m s^-2
export const M_AIR = 0.0289644;          // kg mol^-1, dry air
export const R_GAS = 8.314462618;        // J mol^-1 K^-1
export const HYDRO = G0 * M_AIR / R_GAS; // K m^-1, about 0.03416

// Refractivity (n - 1) of standard dry air: 15 C, 101325 Pa, 450 ppm CO2.
// Ciddor (1996) Appl. Opt. 35, 1566, eq. (1): 1e8 (n_as - 1) = k1/(k0 - s2) + k3/(k2 - s2),
// s = 1/lambda in inverse micrometres.
export function refractivityStandardAir(lambdaMicrons) {
  const s2 = 1 / (lambdaMicrons * lambdaMicrons);
  return (5792105 / (238.0185 - s2) + 167917 / (57.362 - s2)) * 1e-8;
}

// c in n - 1 = c * P[hPa] / T[K], fixed at the standard state.
export function refractivityConstant(lambdaMicrons = 0.55) {
  return refractivityStandardAir(lambdaMicrons) * 288.15 / 1013.25;
}

// ---------------------------------------------------------------------------
// Temperature profiles. A profile is { T(z), dT(z) } in kelvin and kelvin per metre,
// built from four named pieces so every preset on the page is inspectable:
//   T0     air temperature at the surface, extrapolated from above (K)
//   lapse  background gradient (K/m), -0.0065 is the standard atmosphere
//   hot    { dT, L }  a surface layer dT warmer at z=0, decaying as exp(-z/L)
//                     (dT < 0 makes a surface colder than the air above it)
//   inv    { dT, z, w } an inversion: temperature rises by dT across a layer centred
//                     at height z, of thickness scale w (a logistic step)
//   duct   { g, top, w } an extra gradient g (K/m) from the surface up to height top,
//                     switched off smoothly over a thickness scale w (a long, even inversion)
//   tropo  height (m) above which temperature stops falling (11000 in the standard atmosphere)
const softplus = (x) => (x > 30 ? x : Math.log1p(Math.exp(x)));
export function makeProfile({ T0 = 288.15, lapse = -0.0065, hot = null, inv = null, duct = null, tropo = 11000 } = {}) {
  const base = (z) => T0 + lapse * Math.min(z, tropo);
  const dbase = (z) => (z < tropo ? lapse : 0);
  const T = (z) => {
    let t = base(z);
    if (hot) t += hot.dT * Math.exp(-Math.max(z, 0) / hot.L);
    if (inv) t += inv.dT / (1 + Math.exp(-(z - inv.z) / inv.w));
    if (duct) t += duct.g * (z - duct.w * softplus((z - duct.top) / duct.w) + duct.w * softplus(-duct.top / duct.w));
    return t;
  };
  const dT = (z) => {
    let d = dbase(z);
    if (hot) d += -hot.dT / hot.L * Math.exp(-Math.max(z, 0) / hot.L);
    if (inv) {
      const e = Math.exp(-(z - inv.z) / inv.w);
      d += inv.dT / inv.w * e / ((1 + e) * (1 + e));
    }
    if (duct) d += duct.g / (1 + Math.exp((z - duct.top) / duct.w));
    return d;
  };
  return { T, dT, params: { T0, lapse, hot, inv, duct, tropo } };
}

// ---------------------------------------------------------------------------
// An atmosphere: profile + surface pressure, with pressure tabulated by integrating the
// hydrostatic equation on a grid fine enough for any layer the presets use.
export function makeAtmosphere(profile, { P0 = 1013.25, lambda = 0.55, zTop = 40000 } = {}) {
  const c = refractivityConstant(lambda);
  // grid: 1 mm steps to 2 m, then 1 cm to 200 m, then 1 m to 5 km, then 20 m to zTop
  const zs = [0];
  const push = (to, h) => { let z = zs[zs.length - 1]; while (z < to - 1e-9) { z = Math.min(to, z + h); zs.push(z); } };
  push(2, 0.001); push(200, 0.01); push(5000, 1); push(zTop, 20);
  const N = zs.length;
  const lnP = new Float64Array(N);
  lnP[0] = Math.log(P0);
  for (let i = 1; i < N; i++) {
    const a = zs[i - 1], b = zs[i], m = (a + b) / 2;
    // Simpson on d(lnP)/dz = -HYDRO / T
    const f = (z) => -HYDRO / profile.T(z);
    lnP[i] = lnP[i - 1] + (b - a) / 6 * (f(a) + 4 * f(m) + f(b));
  }
  const Z = Float64Array.from(zs);
  function idx(z) {
    // binary search in the non-uniform grid
    let lo = 0, hi = N - 1;
    if (z <= 0) return 0;
    if (z >= Z[hi]) return hi - 1;
    while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (Z[mid] <= z) lo = mid; else hi = mid; }
    return lo;
  }
  function P(z) {
    if (z <= 0) return P0 * Math.exp(HYDRO * -z / profile.T(0)); // below grid: extrapolate
    if (z >= zTop) return Math.exp(lnP[N - 1]) * Math.exp(-HYDRO * (z - zTop) / profile.T(zTop));
    const i = idx(z), t = (z - Z[i]) / (Z[i + 1] - Z[i]);
    return Math.exp(lnP[i] + t * (lnP[i + 1] - lnP[i]));
  }
  // n - 1 and its vertical derivative, analytically from T, dT/dz and hydrostatics:
  //   d(n-1)/dz = (n-1) * ( -HYDRO/T - T'/T )
  function nm1(z) { return c * P(z) / profile.T(z); }
  function n(z) { return 1 + nm1(z); }
  function dndz(z) { const t = profile.T(z); return nm1(z) * (-HYDRO / t - profile.dT(z) / t); }
  return { profile, P0, lambda, c, zTop, P, n, nm1, dndz, T: profile.T, dT: profile.dT };
}

// Ray curvature (1/m) of a horizontal ray at height z, and the refraction coefficient
// k = ray curvature / Earth curvature, the number surveyors use.
export function rayCurvature(atm, z) { return -atm.dndz(z) / atm.n(z); }
export function refractionCoefficient(atm, z) { return rayCurvature(atm, z) * R_EARTH; }

// The temperature gradient at which a horizontal ray bends exactly as much as the Earth
// does (k = 1): light then runs parallel to the sea all the way round. Solved from
//   c P/T^2 * (HYDRO + dT/dz) = 1 / R_EARTH  (dropping the factor 1/n, which is 1 - 3e-4).
export function criticalGradient(T, P, lambda = 0.55) {
  const c = refractivityConstant(lambda);
  return T * T / (c * P * R_EARTH) - HYDRO;
}

// ---------------------------------------------------------------------------
// Trace one ray. Starts at height z0 with elevation alpha (radians, + is up).
// Stops at the first of: reaching arc distance sStop along the surface (returns z there),
// hitting the ground, climbing above zEsc while rising, or travelling maxDist.
// Returns { fate, z, dist, th, phi, invDrift, path? } where fate is
//   'reached' | 'ground' | 'escaped' | 'trapped'.
export function trace(atm0, z0, alpha, opts = {}) {
  const {
    stopAt = Infinity,         // arc distance along the surface (m) to stop and report z
    zEsc = atm0.zTop,          // escape height
    maxDist = 4e6,             // give up (trapped) after this arc distance
    record = 0,                // record a path point every `record` metres of arc (0 = off)
    dsMax = 2000,
    mark = -1,                 // report the last arc distance at which the ray was below this height
    edge = Infinity,           // arc distance at which the air changes to `atmFar` ...
    atmFar = null,             // ... (a layer of finite horizontal extent; see below)
    acc = 0.02,                // step-size factor: smaller is finer (the verifier halves it)
  } = opts;
  // A layer that ends: out to arc distance `edge` the ray moves through atm0, beyond it
  // through atmFar. The boundary is a vertical surface, so crossing it keeps the vertical
  // component of n times the ray direction (Snell's law at a vertical interface):
  //   n0 sin(th0) = n1 sin(th1).  The index jump is about 1e-5, so the kink is tiny;
  // what matters is that beyond the edge the trapping layer is gone.
  let atm = atm0;
  let lastBelow = z0 < mark ? 0 : -1;
  let r = R_EARTH + z0, phi = 0, th = alpha;
  let inv0 = atm.n(z0) * r * Math.cos(alpha), drift = 0;
  const path = record ? [[0, z0]] : null;
  let nextRec = record;
  const deriv = (r_, th_) => {
    const z = r_ - R_EARTH;
    const nn = atm.n(z);
    return [Math.sin(th_), Math.cos(th_) / r_, Math.cos(th_) * (1 / r_ + atm.dndz(z) / nn)];
  };
  let steps = 0;
  while (steps++ < 2e6) {
    const z = r - R_EARTH;
    // step size: small where the ray is low or steep through thin layers
    const sinA = Math.abs(Math.sin(th));
    let ds = Math.min(dsMax, Math.max(acc * 2.5, acc * (z + 0.05) / Math.max(sinA, 1e-5)));
    // do not overshoot the stop distance or the edge of the layer
    const arc = phi * R_EARTH;
    const wall = atm === atm0 && atmFar ? Math.min(stopAt, edge) : stopAt;
    if (arc + ds * Math.cos(th) > wall) ds = Math.max((wall - arc) / Math.max(Math.cos(th), 1e-9), 1e-6);
    // RK4
    const k1 = deriv(r, th);
    const k2 = deriv(r + ds / 2 * k1[0], th + ds / 2 * k1[2]);
    const k3 = deriv(r + ds / 2 * k2[0], th + ds / 2 * k2[2]);
    const k4 = deriv(r + ds * k3[0], th + ds * k3[2]);
    const rN = r + ds / 6 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]);
    const pN = phi + ds / 6 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]);
    const tN = th + ds / 6 * (k1[2] + 2 * k2[2] + 2 * k3[2] + k4[2]);
    const zN = rN - R_EARTH;
    if (zN < 0) {
      // interpolate the ground hit
      const f = z / (z - zN);
      const dist = (phi + f * (pN - phi)) * R_EARTH;
      if (path) path.push([dist, 0]);
      return finish('ground', 0, dist, th + f * (tN - th), phi + f * (pN - phi));
    }
    r = rN; phi = pN; th = tN;
    const dist = phi * R_EARTH;
    if (zN < mark) lastBelow = dist;
    if (path && dist >= nextRec) { path.push([dist, zN]); nextRec += record; }
    if (dist >= stopAt - 1e-6) return finish('reached', zN, dist, th, phi);
    if (atmFar && atm === atm0 && dist >= edge - 1e-6) {
      // cross the vertical boundary
      const nA = atm0.n(zN), nB = atmFar.n(zN);
      drift = Math.max(drift, Math.abs((nA * r * Math.cos(th) - inv0) / inv0));
      th = Math.asin(clampUnit(nA / nB * Math.sin(th)));
      atm = atmFar;
      inv0 = nB * r * Math.cos(th);
    }
    if (zN > zEsc && th > 0) return finish('escaped', zN, dist, th, phi);
    if (dist > maxDist) return finish('trapped', zN, dist, th, phi);
  }
  return finish('trapped', r - R_EARTH, phi * R_EARTH, th, phi);

  function finish(fate, z, dist, thE, phiE) {
    const inv = atm.n(z) * (R_EARTH + z) * Math.cos(thE);
    if (path && (path.length === 0 || path[path.length - 1][0] !== dist)) path.push([dist, z]);
    if (z < mark) lastBelow = dist;
    drift = Math.max(drift, Math.abs((inv - inv0) / inv0));
    return { fate, z, dist, th: thE, phi: phiE, invDrift: drift, path, lastBelow };
  }
}
const clampUnit = (x) => Math.max(-1, Math.min(1, x));

// ---------------------------------------------------------------------------
// Terrestrial scene: for each apparent elevation alpha (radians) seen by an eye at height
// zEye, where does the ray cross the vertical plane at arc distance D, and what does it
// finally land on? Returns rows of { alpha, hAtD (m, or null if the ray met the ground
// first), fate ('ground' | 'escaped' | 'far'), dist, exitTh (elevation when it left) }.
export function transfer(atm, zEye, D, alphas, { beyond = 6, dsMax, zEsc = 2000 } = {}) {
  const ds = dsMax ?? Math.max(D / 300, 0.5);
  const out = [];
  for (const a of alphas) {
    // one trace to the target plane, then (if the ray got there) a second to learn what
    // lies behind it: the sky, the far ground, or nothing yet (still in the air)
    const first = trace(atm, zEye, a, { stopAt: D, dsMax: ds, zEsc });
    const row = { alpha: a, hAtD: null, fate: first.fate, dist: first.dist, exitTh: null, invDrift: first.invDrift };
    let fin = first;
    if (first.fate === 'reached') {
      row.hAtD = first.z;
      fin = trace(atm, zEye, a, { maxDist: D * beyond, dsMax: ds, zEsc });
      row.fate = fin.fate === 'trapped' ? 'far' : fin.fate;
      row.dist = fin.dist;
    }
    // where the ray was when we stopped following it: a ray still climbing at the far end
    // is sky, a ray still descending is distant ground (the renderer's rule, stated here)
    row.exitTh = fin.th;
    row.endZ = fin.z;
    out.push(row);
  }
  return out;
}

// Celestial scene: for each apparent elevation, the true direction in the observer's own
// horizon frame that the ray came from (radians), or null if the ray ends on the ground
// or is still trapped after maxDist. Also returns the arc distance travelled in the
// atmosphere before escaping, the length of air the light had to cross.
export function skyMap(atm, zEye, alphas, { maxDist = 3e6, dsMax = 2000, mark = -1, edge = Infinity, atmFar = null } = {}) {
  return alphas.map((a) => {
    const t = trace(atm, zEye, a, { maxDist, dsMax, mark, edge, atmFar });
    if (t.fate !== 'escaped') return { alpha: a, trueElev: null, fate: t.fate, dist: t.dist, lastBelow: t.lastBelow };
    // Above zTop the remaining bending is below 1e-7 rad for any escape angle used here,
    // so the direction at zTop, rotated back by the arc travelled, is the true direction.
    return { alpha: a, trueElev: t.th - t.phi, fate: t.fate, dist: t.dist, lastBelow: t.lastBelow };
  });
}

// ---------------------------------------------------------------------------
// The Sun, low-precision (Meeus, Astronomical Algorithms 2nd ed., ch. 25, accurate to
// about 0.01 degree), and its altitude at a place and time. jd is a Julian Day (UT/TT;
// the difference, under three minutes in 1597, is irrelevant at this precision).
export function julianDayGregorian(y, m, d) {
  if (m <= 2) { y -= 1; m += 12; }
  const A = Math.floor(y / 100), B = 2 - A + Math.floor(A / 4);
  return Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d + B - 1524.5;
}
export function julianDayJulian(y, m, d) {
  if (m <= 2) { y -= 1; m += 12; }
  return Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d - 1524.5;
}
const DEG = Math.PI / 180;
export function sunPosition(jd) {
  const T = (jd - 2451545.0) / 36525;
  const L0 = 280.46646 + 36000.76983 * T + 0.0003032 * T * T;
  const M = 357.52911 + 35999.05029 * T - 0.0001537 * T * T;
  const C = (1.914602 - 0.004817 * T - 0.000014 * T * T) * Math.sin(M * DEG)
    + (0.019993 - 0.000101 * T) * Math.sin(2 * M * DEG) + 0.000289 * Math.sin(3 * M * DEG);
  const lon = L0 + C;
  const omega = 125.04 - 1934.136 * T;
  const lambda = lon - 0.00569 - 0.00478 * Math.sin(omega * DEG);
  const eps0 = 23 + 26 / 60 + 21.448 / 3600 - (46.815 * T + 0.00059 * T * T - 0.001813 * T * T * T) / 3600;
  const eps = eps0 + 0.00256 * Math.cos(omega * DEG);
  const dec = Math.asin(Math.sin(eps * DEG) * Math.sin(lambda * DEG));
  const ra = Math.atan2(Math.cos(eps * DEG) * Math.sin(lambda * DEG), Math.cos(lambda * DEG));
  // Greenwich mean sidereal time (Meeus 12.4), degrees
  const gmst = 280.46061837 + 360.98564736629 * (jd - 2451545) + 0.000387933 * T * T - T * T * T / 38710000;
  return { dec, ra, gmst: ((gmst % 360) + 360) % 360 };
}
// True (geometric, unrefracted) altitude of the Sun's centre, radians. lonEast in degrees.
export function sunAltitude(jd, latDeg, lonEastDeg) {
  const { dec, ra, gmst } = sunPosition(jd);
  const H = (gmst + lonEastDeg) * DEG - ra;
  const lat = latDeg * DEG;
  return Math.asin(Math.sin(lat) * Math.sin(dec) + Math.cos(lat) * Math.cos(dec) * Math.cos(H));
}
// Highest true altitude of the Sun's centre during the UT day starting at jd0 (00h UT).
export function sunHighest(jd0, latDeg, lonEastDeg) {
  let best = -Infinity, when = jd0;
  for (let k = 0; k <= 1440; k++) {
    const jd = jd0 + k / 1440;
    const a = sunAltitude(jd, latDeg, lonEastDeg);
    if (a > best) { best = a; when = jd; }
  }
  return { alt: best, jd: when };
}

// Bennett (1982) refraction for apparent altitude h0 (degrees), in arcminutes, the formula
// the Astronomical Almanac tradition uses for 10 C and 1010 hPa (Meeus eq. 16.4).
export function bennettRefraction(h0Deg) {
  return 1 / Math.tan((h0Deg + 7.31 / (h0Deg + 4.4)) * DEG);
}

// ---------------------------------------------------------------------------
// The presets the page offers, in one place so the verifier checks the same ones.
export const PRESETS = {
  standard: {
    label: 'Standard atmosphere',
    profile: { T0: 288.15, lapse: -0.0065 },
    P0: 1013.25,
  },
  road: {
    label: 'Hot road',
    // air 30 C, road surface air 18 K hotter, the excess halving every ~5.5 cm
    profile: { T0: 303.15, lapse: -0.0065, hot: { dT: 18, L: 0.08 } },
    P0: 1013.25,
  },
  sea: {
    label: 'Cold sea, warm air aloft',
    // sea surface air 2 C, an inversion of +8 K centred 30 m up
    profile: { T0: 275.15, lapse: -0.0065, inv: { dT: 8, z: 30, w: 6 } },
    P0: 1013.25,
  },
  arctic: {
    label: 'Arctic duct',
    // -30 C at the ice, +12 K across a layer centred 60 m up
    profile: { T0: 243.15, lapse: -0.0065, inv: { dT: 12, z: 60, w: 12 } },
    P0: 1013.25,
  },
};
export function presetAtmosphere(name, lambda = 0.55) {
  const p = PRESETS[name];
  return makeAtmosphere(makeProfile(p.profile), { P0: p.P0, lambda });
}
