// Parsing and measurement physics for why-does-dew-form. The surface model lives in engine.mjs
// (shared with the page); the vapour-pressure formulas are imported from there so they exist once.
import { SIGMA, esWater, esIce } from '../engine.mjs';
export { SIGMA, esWater, esIce };
export const LV = 2.45e6;              // latent heat of condensation near 20 C, J/kg
export const LS = 2.834e6;             // latent heat of deposition (vapour to ice), J/kg
export const EPS_GRASS = 0.98;         // assumed longwave emissivity of the field (varied in the robustness grid)

// Dew point (C) from air temperature (C) and RH (%), the inverse of esWater.
export function dewPoint(tC, rh) {
  const a = 17.625, b = 243.04, g = Math.log(rh / 100) + (a * tC) / (b + tC);
  return (b * g) / (a - g);
}
// Radiating ("brightness") temperature of a flux, treating the emitter as a black body.
export const radTemp = (flux) => Math.pow(flux / SIGMA, 0.25) - 273.15;
// Surface temperature from the downward-looking pyrgeometer: uw = eps*sigma*Ts^4 + (1-eps)*dw.
export function surfTemp(uw, dw, eps = EPS_GRASS) {
  return Math.pow((uw - (1 - eps) * dw) / (eps * SIGMA), 0.25) - 273.15;
}
export const eAir = (t, rh) => (rh / 100) * esWater(t);
// Can water leave the air onto a surface at ts? Liquid (dew) at or above 0 C, ice (hoar frost) below.
// margin (C) moves the surface warmer (+) or colder (-) to test how much a verdict rests on sensor error.
export function deposits(ts, ta, rh, margin = 0) {
  const t = ts + margin, e = eAir(ta, rh);
  if (t >= 0) return e > esWater(t) ? 'dew' : null;
  return e > esIce(t) ? 'frost' : null;
}

// Parse one SURFRAD daily file (layout in README_SURFRAD.txt). Values whose QC flag is not 0,
// or that are the -9999.9 missing marker, become null.
export function parseSurfrad(text) {
  const lines = text.split(/\r?\n/);
  const name = lines[0].trim();
  const [lat, lon, elev] = lines[1].trim().split(/\s+/).map(Number);
  const rows = [];
  for (let i = 2; i < lines.length; i++) {
    const p = lines[i].trim().split(/\s+/);
    if (p.length < 48) continue;
    const n = p.map(Number);
    // after zen (index 7) come 20 value/flag pairs: dw_solar uw_solar direct_n diffuse dw_ir dw_casetemp
    // dw_dometemp uw_ir uw_casetemp uw_dometemp uvb par netsolar netir totalnet temp rh windspd winddir pressure
    const v = (k) => { const val = n[8 + 2 * k], qc = n[9 + 2 * k]; return (qc !== 0 || val <= -9999) ? null : val; };
    rows.push({ year: n[0], jday: n[1], month: n[2], day: n[3], hour: n[4], min: n[5], zen: n[7],
      dw_ir: v(4), uw_ir: v(7), temp: v(15), rh: v(16), wind: v(17), pressure: v(19) });
  }
  return { name, lat, lon, elev, rows };
}
export const tUTC = (r) => Date.UTC(r.year, r.month - 1, r.day, r.hour, r.min) / 60000;   // minutes since 1970
