// Every number the page prints is computed here, from parsed SURFRAD rows. Pure functions only;
// build.mjs does the fetching and writing, verify-why-does-dew-form.mjs re-runs and compares.
import { parseSurfrad, surfTemp, radTemp, dewPoint, deposits, tUTC, SIGMA, LV, EPS_GRASS } from './lib.mjs';
import { balance } from '../engine.mjs';

// Local standard time offsets (hours) used only for labelling nights by their evening date.
export const UTC_OFFSET = { bon: -6, dra: -8 };
const r2 = (x, d = 2) => Math.round(x * 10 ** d) / 10 ** d;
const quant = (a, p) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(p * (s.length - 1))]; };

export function loadRows(texts) {
  let rows = [], meta = null;
  for (const t of texts) { const d = parseSurfrad(t); meta = meta || d; rows.push(...d.rows); }
  rows.sort((a, b) => tUTC(a) - tUTC(b));
  return { meta, rows };
}
const complete = (r) => r.dw_ir != null && r.uw_ir != null && r.temp != null && r.rh != null && r.rh > 0 && r.wind != null;

// Nights: contiguous runs of solar zenith > 96 deg (after civil dusk, before civil dawn), gaps <= 30 min.
export function splitNights(rows, st) {
  const nights = []; let cur = null, last = -1e9;
  for (const r of rows) {
    if (r.zen <= 96) continue;
    const t = tUTC(r);
    if (!cur || t - last > 30) { cur = { start: t, rows: [] }; nights.push(cur); }
    cur.rows.push(r); last = t;
  }
  for (const n of nights) {
    const local = new Date((n.start + UTC_OFFSET[st] * 60) * 60000);
    n.localDate = local.toISOString().slice(0, 10);          // the evening the night began, local standard time
  }
  return nights;
}

// One night's summary. Only complete minutes count, and a night must be >= 300 min long and >= 80% complete.
export function summarise(n, { eps = EPS_GRASS, margin = 0 } = {}) {
  const ok = n.rows.filter(complete);
  if (n.rows.length < 300 || ok.length < 0.8 * n.rows.length) return null;
  let dew = 0, frost = 0, ceilJ = 0, firstCold = null, firstDep = null, sDef = 0, sSky = 0, sW = 0, sA = 0, sD = 0, minDef = 1e9;
  const epsSky = [];
  for (const r of ok) {
    const ts = surfTemp(r.uw_ir, r.dw_ir, eps), dep = deposits(ts, r.temp, r.rh, margin);
    if (dep === 'dew') dew++; else if (dep === 'frost') frost++;
    const m = tUTC(r) - n.start;                                // minutes after civil dusk
    if (firstCold == null && ts < r.temp - 1) firstCold = m;
    if (firstDep == null && dep) firstDep = m;
    // energy ceiling on condensation: only minutes when the surface is colder than the air, so the air
    // and (assumed) the soil are both feeding heat IN; then every joule of latent heat must leave as net IR.
    if (ts < r.temp && r.uw_ir > r.dw_ir) ceilJ += (r.uw_ir - r.dw_ir) * 60;
    sDef += ts - r.temp; sSky += radTemp(r.dw_ir) - r.temp; sW += r.wind; sA += r.temp; sD += dewPoint(r.temp, r.rh);
    minDef = Math.min(minDef, ts - r.temp);
    epsSky.push(r.dw_ir / (SIGMA * (r.temp + 273.15) ** 4));
  }
  const k = ok.length;
  return { date: n.localDate, minutes: k, epsSky: r2(quant(epsSky, 0.5), 3),
    skyMinusAir: r2(sSky / k), surfMinusAir: r2(sDef / k), minSurfMinusAir: r2(minDef), wind: r2(sW / k),
    air: r2(sA / k), dewPoint: r2(sD / k), dewMin: dew, frostMin: frost, condMin: dew + frost,
    ceilingMm: r2(ceilJ / LV, 3), firstColdMin: firstCold, firstDepMin: firstDep };
}

export function stationNights(rows, st, opts) {
  return splitNights(rows, st).map(n => summarise(n, opts)).filter(Boolean);
}

// Wells's cloud: 20-minute windows where the sky's IR rises >= 30 W/m2 and the surface warms >= 2 C
// while the air changes by no more than 1.5 C. Strongest first, one per 3 hours.
export function cloudEvents(rows, st) {
  const night = rows.filter(r => r.zen > 96 && complete(r));
  const byT = new Map(night.map(r => [tUTC(r), r]));
  const ev = [];
  for (const r of night) {
    const t0 = tUTC(r), r1 = byT.get(t0 + 20); if (!r1) continue;
    const dTs = surfTemp(r1.uw_ir, r1.dw_ir) - surfTemp(r.uw_ir, r.dw_ir), dSky = r1.dw_ir - r.dw_ir, dTa = r1.temp - r.temp;
    if (dTs >= 2 && dSky >= 30 && Math.abs(dTa) <= 1.5) ev.push({ t0, dTs, dSky, dTa, air: r.temp, sky0: radTemp(r.dw_ir), sky1: radTemp(r1.dw_ir) });
  }
  ev.sort((a, b) => b.dTs - a.dTs || a.t0 - b.t0);
  const kept = [];
  for (const e of ev) if (!kept.some(k => Math.abs(k.t0 - e.t0) < 180)) kept.push(e);
  return kept.map(e => ({ utc: new Date(e.t0 * 60000).toISOString().slice(0, 16),
    local: new Date((e.t0 + UTC_OFFSET[st] * 60) * 60000).toISOString().slice(0, 16),
    surfaceWarmedC: r2(e.dTs), skyIRRoseW: r2(e.dSky, 1), airChangedC: r2(e.dTa), air: r2(e.air, 1),
    skyBefore: r2(e.sky0, 1), skyAfter: r2(e.sky1, 1) }));
}

// Wells's table: nights split by thirds of sky emissivity and of wind.
export function thirds(N, minMin = 60) {
  const e1 = quant(N.map(n => n.epsSky), 1 / 3), e2 = quant(N.map(n => n.epsSky), 2 / 3);
  const w1 = quant(N.map(n => n.wind), 1 / 3), w2 = quant(N.map(n => n.wind), 2 / 3);
  const skies = [['clearest third', n => n.epsSky <= e1], ['middle', n => n.epsSky > e1 && n.epsSky < e2], ['cloudiest third', n => n.epsSky >= e2]];
  const winds = [['calmest third', n => n.wind <= w1], ['middle', n => n.wind > w1 && n.wind < w2], ['windiest third', n => n.wind >= w2]];
  const cells = [];
  for (const [sk, fs] of skies) for (const [wk, fw] of winds) {
    const c = N.filter(n => fs(n) && fw(n));
    cells.push({ sky: sk, wind: wk, nights: c.length, condNights: c.filter(n => n.condMin >= minMin).length,
      meanSurfMinusAir: c.length ? r2(c.reduce((s, n) => s + n.surfMinusAir, 0) / c.length) : null,
      medianDewDepression: c.length ? r2(quant(c.map(n => n.air - n.dewPoint), 0.5), 1) : null });
  }
  return { cuts: { eps: [e1, e2], wind: [r2(w1), r2(w2)] }, cells };
}

// The thin-surface model against the measured field, every 10th night minute: odd vs even days
// (nothing is fitted, so the split only shows the error is stable), and by 10 m wind speed.
export const WIND_BINS = [[0, 2], [2, 4], [4, 6], [6, 99]];
export function validate(rows, ks = [1], form = 'mcadams') {
  const out = {};
  for (const k of ks) {
    const acc = { odd: [0, 0, 0], even: [0, 0, 0] }, byWind = WIND_BINS.map(() => [0, 0, 0]);
    for (const r of rows) {
      if (r.zen <= 96 || r.min % 10 || !complete(r)) continue;
      const meas = surfTemp(r.uw_ir, r.dw_ir);
      const d = balance({ dw: r.dw_ir, ta: r.temp, rh: r.rh, u10: r.wind, p: r.pressure || 1000 }, { k, form }).ts - meas;
      const a = acc[r.jday % 2 ? 'odd' : 'even']; a[0]++; a[1] += d; a[2] += d * d;
      const w = byWind[WIND_BINS.findIndex(([lo, hi]) => r.wind >= lo && r.wind < hi)]; w[0]++; w[1] += d; w[2] += d * d;
    }
    const f = ([n, s, s2]) => ({ n, bias: r2(s / n), rmse: r2(Math.sqrt(s2 / n)) });
    out[k] = { ...Object.fromEntries(Object.entries(acc).map(([p, a]) => [p, f(a)])),
      byWind: WIND_BINS.map(([lo, hi], i) => ({ wind: hi > 50 ? `>= ${lo}` : `${lo}-${hi}`, ...f(byWind[i]) })) };
  }
  return out;
}

// A night as columns every 2 minutes, for the page's charts and its live model.
export function trace(night) {
  const cols = { m: [], ta: [], td: [], tsky: [], ts: [], dw: [], rh: [], u: [], p: [] };
  for (const r of night.rows) {
    const m = tUTC(r) - night.start;
    if (m % 2 || !complete(r)) continue;
    cols.m.push(m); cols.ta.push(r2(r.temp, 1)); cols.td.push(r2(dewPoint(r.temp, r.rh), 2));
    cols.tsky.push(r2(radTemp(r.dw_ir), 1)); cols.ts.push(r2(surfTemp(r.uw_ir, r.dw_ir), 2));
    cols.dw.push(r2(r.dw_ir, 1)); cols.rh.push(r2(r.rh, 1)); cols.u.push(r2(r.wind, 1)); cols.p.push(Math.round(r.pressure || 1000));
  }
  return cols;
}
