// engine.mjs: the physics the page runs, and the verifier imports.
//
// One idea, exact: a daily temperature cycle pressed onto the surface of a solid
// travels inward as a damped, delayed wave (Fourier 1822; the cellar problem).
// Harmonic n of a cycle with angular frequency w decays as exp(-x/d_n) and lags
// by x/d_n radians, with d_n = sqrt(2 k / (n w)). A thin wall passes the day
// almost unchanged; a thick one keeps only the daily mean. Two air columns behind
// walls of different thickness therefore swap which one is warmer twice a day,
// and warm air rises in the warmer column: a pump driven by the sun, not by the
// colony. Everything below is that sentence made computable.

export const DAY = 86400;               // s
export const OMEGA = 2 * Math.PI / DAY; // rad/s
export const G = 9.81;                  // m/s^2

// Penetration depth of harmonic n in a solid of thermal diffusivity kappa (m^2/s).
export function depth(kappa, n = 1, period = DAY) {
  return Math.sqrt((2 * kappa) / (n * 2 * Math.PI / period));
}

// Real Fourier series of one period of evenly spaced samples.
// Returns { mean, a:[..], b:[..] } with f(t) = mean + sum a_n cos(n w t) + b_n sin(n w t),
// t in seconds from the first sample, n = 1..N.
export function fourier(samples, N = 6, period = DAY) {
  const M = samples.length;
  const w = 2 * Math.PI / period;
  const dt = period / M;
  let mean = 0;
  for (const s of samples) mean += s;
  mean /= M;
  const a = [], b = [];
  for (let n = 1; n <= N; n++) {
    let ca = 0, cb = 0;
    for (let i = 0; i < M; i++) {
      const t = i * dt;
      ca += samples[i] * Math.cos(n * w * t);
      cb += samples[i] * Math.sin(n * w * t);
    }
    a.push((2 / M) * ca);
    b.push((2 / M) * cb);
  }
  return { mean, a, b, period };
}

export function evalSeries(c, t) {
  const w = 2 * Math.PI / c.period;
  let v = c.mean;
  for (let i = 0; i < c.a.length; i++) {
    const n = i + 1;
    v += c.a[i] * Math.cos(n * w * t) + c.b[i] * Math.sin(n * w * t);
  }
  return v;
}

// The surface series carried to depth x inside a semi-infinite solid (exact for
// each harmonic): each term shrinks by exp(-x/d_n) and is delayed by x/d_n rad.
export function atDepth(c, x, kappa) {
  const a = [], b = [];
  for (let i = 0; i < c.a.length; i++) {
    const n = i + 1;
    const d = depth(kappa, n, c.period);
    const damp = Math.exp(-x / d), lag = x / d;
    // a cos(nwt) + b sin(nwt)  ->  damp * [a cos(nwt - lag) + b sin(nwt - lag)]
    const cl = Math.cos(lag), sl = Math.sin(lag);
    a.push(damp * (a_(c, i) * cl - c.b[i] * sl));
    b.push(damp * (c.b[i] * cl + a_(c, i) * sl));
  }
  return { mean: c.mean, a, b, period: c.period };
}
const a_ = (c, i) => c.a[i];

// Sign changes of f on [t0, t1), located by bisection. Returns [{t, dir}] with dir
// +1 where f goes from negative to positive.
export function zeroCrossings(f, t0, t1, steps = 2880) {
  const out = [];
  const h = (t1 - t0) / steps;
  let tp = t0, fp = f(t0);
  for (let k = 1; k <= steps; k++) {
    const t = t0 + k * h, v = f(t);
    if ((fp < 0 && v >= 0) || (fp > 0 && v <= 0)) {
      let lo = tp, hi = t, flo = fp;
      for (let j = 0; j < 60; j++) {
        const m = (lo + hi) / 2, fm = f(m);
        if ((flo < 0) === (fm < 0)) { lo = m; flo = fm; } else hi = m;
      }
      out.push({ t: (lo + hi) / 2, dir: fp < 0 ? 1 : -1 });
    }
    tp = t; fp = v;
  }
  return out;
}

// Stack-effect pressure between two columns of height H (m) at T1, T2 (degC),
// ideal gas at fixed pressure p0: dp = p0 M g H / R * (1/T2 - 1/T1), positive
// when column 1 is warmer (its air is lighter, so it rises).
export function stackPressure(H, T1c, T2c, p0 = 101325) {
  const M = 0.028964, R = 8.314462618;
  const T1 = T1c + 273.15, T2 = T2c + 273.15;
  return (p0 * M * G * H / R) * (1 / T2 - 1 / T1);
}

// ── reading a plotted curve ─────────────────────────────────────────────────

// Linear interpolation of a curve given as [[hour, value], ...] (hours ascending).
export function interp(pts, h) {
  if (h <= pts[0][0]) return pts[0][1];
  for (let k = 0; k < pts.length - 1; k++) {
    const [x0, y0] = pts[k], [x1, y1] = pts[k + 1];
    if (h <= x1) return x1 > x0 ? y0 + (y1 - y0) * (h - x0) / (x1 - x0) : y0;
  }
  return pts[pts.length - 1][1];
}

// Resample a one-day curve onto M even steps. A plotted day rarely closes on itself
// (the end is not exactly the start), so the straight-line drift between the two ends
// is removed first, so the Fourier series does not read that jump as a daily wave.
export function daySamples(pts, M = 1440) {
  const drift = pts[pts.length - 1][1] - pts[0][1];
  const s = [];
  for (let k = 0; k < M; k++) s.push(interp(pts, 24 * k / M) - drift * (k / M - 0.5));
  return s;
}

// Harmonic n of a series as a complex number [re, im] = (a_n, -b_n) convention:
// value(t) contains |c| cos(n w t - phase), phase = atan2(b_n, a_n).
export function harmonic(c, n) { return [c.a[n - 1], c.b[n - 1]]; }
export function amp(h) { return Math.hypot(h[0], h[1]); }
export function phase(h) { return Math.atan2(h[1], h[0]); }
// Hour of day at which harmonic n of a daily series peaks.
export function peakHour(h, n = 1) {
  const p = phase(h) / (2 * Math.PI * n) * 24;
  return ((p % (24 / n)) + 24 / n) % (24 / n);
}

// ── the same filter in three shapes ────────────────────────────────────────
// A periodic temperature on the outside of a body reaches a point inside it
// multiplied by a complex factor: its size is the damping, its angle the delay.
// q = (1+i) R / d, with R the distance (or radius) and d the penetration depth.
//   flat ground, depth R:           exp(-q)
//   centre of a slab, half-width R: 1 / cosh(q)
//   axis of a long cylinder, radius R: 1 / I0(q)
// For flat ground the damping and the delay are the same number (e^-x and x rad).
// For a body heated from every side the centre is always LESS damped than that
// for the same delay, because heat arrives from all around at once.
function cmul(a, b) { return [a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0]]; }
function cdiv(a, b) { const d = b[0] * b[0] + b[1] * b[1]; return [(a[0] * b[0] + a[1] * b[1]) / d, (a[1] * b[0] - a[0] * b[1]) / d]; }
function cexp(a) { const e = Math.exp(a[0]); return [e * Math.cos(a[1]), e * Math.sin(a[1])]; }
function I0(z) { // series sum_k (z/2)^(2k) / (k!)^2
  const z2 = cmul([z[0] / 2, z[1] / 2], [z[0] / 2, z[1] / 2]);
  let term = [1, 0], sum = [1, 0];
  for (let k = 1; k < 200; k++) {
    term = cmul(term, z2); term = [term[0] / (k * k), term[1] / (k * k)];
    sum = [sum[0] + term[0], sum[1] + term[1]];
    if (Math.hypot(term[0], term[1]) < 1e-17 * Math.hypot(sum[0], sum[1])) break;
  }
  return sum;
}
export function response(shape, r) { // r = R / d
  const q = [r, r];
  if (shape === 'flat') return cexp([-r, -r]);
  if (shape === 'slab') { const e1 = cexp(q), e2 = cexp([-r, -r]); return cdiv([2, 0], [e1[0] + e2[0], e1[1] + e2[1]]); }
  if (shape === 'cylinder') return cdiv([1, 0], I0(q));
  throw new Error('unknown shape ' + shape);
}
// Damping (size) and delay (radians, positive = later) of a response.
export function dampDelay(z) { return { damp: Math.hypot(z[0], z[1]), delay: -Math.atan2(z[1], z[0]) }; }
// The distance R/d at which a shape delays by `delay` radians. The angle is
// unwrapped by walking outward in small steps (it passes pi for thick bodies),
// then the crossing step is refined by bisection.
export function unwrappedDelay(shape, r, step = 0.01) {
  let acc = 0, prev = 0;
  for (let x = step; x <= r + 1e-12; x += step) {
    const d = dampDelay(response(shape, x)).delay;
    let dd = d - prev; while (dd > Math.PI) dd -= 2 * Math.PI; while (dd < -Math.PI) dd += 2 * Math.PI;
    acc += dd; prev = d;
  }
  const d = dampDelay(response(shape, r)).delay;
  let dd = d - prev; while (dd > Math.PI) dd -= 2 * Math.PI; while (dd < -Math.PI) dd += 2 * Math.PI;
  return acc + dd;
}
export function rForDelay(shape, delay) {
  let lo = 0, hi = 0.01;
  while (unwrappedDelay(shape, hi) < delay) { lo = hi; hi += 0.01; if (hi > 50) throw new Error('no crossing'); }
  for (let j = 0; j < 60; j++) {
    const m = (lo + hi) / 2;
    if (unwrappedDelay(shape, m) < delay) lo = m; else hi = m;
  }
  return (lo + hi) / 2;
}

// ── the page's readings, computed from data.json ───────────────────────────
export const SIDES = ['north', 'east', 'south', 'west'];
const YEAR = 365.25 * DAY;

export function curveStats(pts) {
  const c = fourier(daySamples(pts), 4);
  const h1 = harmonic(c, 1);
  return { mean: c.mean, amp: amp(h1), peak: peakHour(h1), c };
}

// The four sides averaged hour by hour (the paper's "average periphery temperature").
export function peripheryCurve(curves, M = 1440) {
  const out = [];
  for (let k = 0; k <= M; k++) {
    const h = 24 * k / M;
    out.push([h, SIDES.reduce((s, n) => s + interp(curves[n], h), 0) / SIDES.length]);
  }
  return out;
}

// Quarterly means centred on the two solstices, as Turner and Marais reported them
// (their "quarterly average temperature ... around the winter solstice"), from a daily
// series with day 0 = 1 January. 91-day windows centred on 21 June and 21 December.
export function solsticeQuarters(daily) {
  const N = daily.length;
  const q = (centre) => { let s = 0; for (let k = -45; k <= 45; k++) s += daily[((centre + k) % N + N) % N]; return s / 91; };
  const summer = q(354), winter = q(171); // 21 Dec is day 354 of a leap year, 21 Jun day 171
  return { summer, winter, span: summer - winter };
}

export function analyse(data, kappa = 0.5e-6) {
  const cv = data.ocko2017.curves;
  const stats = Object.fromEntries(Object.keys(cv).map((n) => [n, curveStats(cv[n])]));
  const per = peripheryCurve(cv);
  const P = curveStats(per);
  const ph1 = harmonic(P.c, 1);
  const rel = (n) => {
    const h = harmonic(stats[n].c, 1);
    const ratio = amp(h) / amp(ph1);
    let delay = phase(h) - phase(ph1); // radians later than the periphery
    while (delay < 0) delay += 2 * Math.PI;
    return { ratio, delay, delayHours: delay / (2 * Math.PI) * 24 };
  };
  const center = rel('center'), nest = rel('nest');
  const dT = (h) => interp(per, h) - interp(cv.center, h);
  const crossings = zeroCrossings(dT, 0, 24, 2400).map((z) => ({ hour: z.t, dir: z.dir }));
  let dTmin = Infinity, dTmax = -Infinity;
  for (let k = 0; k < 2400; k++) { const v = dT(24 * k / 2400); dTmin = Math.min(dTmin, v); dTmax = Math.max(dTmax, v); }
  const dDay = depth(kappa), dYear = depth(kappa, 1, YEAR);
  const need = Object.fromEntries(['flat', 'cylinder'].map((s) => {
    const r = rForDelay(s, center.delay);
    return [s, { rOverD: r, cm: 100 * r * dDay, damp: dampDelay(response(s, r)).damp }];
  }));
  const q = solsticeQuarters(data.omatjenne2004.skinTemperature);
  return {
    kappa, dDay, dYear, stats, periphery: P, center, nest, need, crossings, dTmin, dTmax,
    nestDailyAt: (x) => Math.exp(-x / dDay),
    nestYearAt: (x) => Math.exp(-x / dYear),
    surfaceQuarters: q,
  };
}
