// The surface model behind the instrument: a thin surface with no heat store (a leaf, a
// grass blade, a car roof), in balance each minute between what it radiates, what it receives
// from the sky and from whatever else it can see, what the air carries to it, and the heat
// released by any water that condenses on it. Shared by the page and the verifier.
export const SIGMA = 5.670374419e-8, CP = 1004, LV = 2.45e6, LS = 2.834e6;
export const esWater = (t) => 6.1094 * Math.exp(17.625 * t / (t + 243.04));
export const esIce = (t) => 6.1121 * Math.exp(22.587 * t / (t + 273.86));
const q = (e, p) => 0.622 * e / (p - 0.378 * e);          // specific humidity from vapour pressure (hPa)

// Wind at the surface's height from the tower's 10 m wind (log profile over short grass).
export function windAt(u10, z = 0.5, z0 = 0.03) { return Math.max(0, u10) * Math.log(z / z0) / Math.log(10 / z0); }
// Convective coefficient of a flat surface, W m^-2 K^-1. The default is the classic form 5.7 + 3.8u
// quoted by McAdams; Watmuff, Charters and Proctor (1977) argued it folds in some radiation and offered
// 2.8 + 3.0u. The page uses the first (chosen before any comparison); the verifier reports both.
export function hConv(u, k = 1, form = 'mcadams') { return k * (form === 'watmuff' ? 2.8 + 3.0 * u : 5.7 + 3.8 * u); }

// One minute. inputs: dw (sky IR, W/m2), ta (C), rh (%), u10 (m/s), p (hPa);
// view: fraction of the surface's hemisphere that is open sky (1 flat and open, 0.5 a vertical wall,
// ~0 under a canopy); the rest is taken to be at air temperature. eps: surface emissivity. k: h multiplier.
// Returns surface temperature and condensation rate (kg m^-2 s^-1, >0 means water arriving).
export function balance({ dw, ta, rh, u10, p = 1000 }, { view = 1, eps = 0.98, k = 1, z = 0.5, form = 'mcadams' } = {}) {
  const Ta = ta + 273.15, h = hConv(windAt(u10, z), k, form);
  const ea = (rh / 100) * esWater(ta), qa = q(ea, p);
  const inIR = eps * (view * dw + (1 - view) * SIGMA * Ta ** 4);
  const f = (ts) => {                                        // net heat into surface at temperature ts
    const es = ts >= 0 ? esWater(ts) : esIce(ts), L = ts >= 0 ? LV : LS;
    const cond = Math.max(0, (h / CP) * (qa - q(es, p)));   // Lewis analogy; condensation only (evaporation off: a dry start)
    return inIR - eps * SIGMA * (ts + 273.15) ** 4 + h * (ta - ts) + L * cond;
  };
  let lo = ta - 40, hi = ta + 5;
  for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; if (f(m) > 0) lo = m; else hi = m; }
  const ts = (lo + hi) / 2, es = ts >= 0 ? esWater(ts) : esIce(ts);
  return { ts, cond: Math.max(0, (h / CP) * (qa - q(es, p))), ice: ts < 0 };
}

// View factor from a small patch of ground to a parallel square of side a centred above it at height h
// (the standard closed form for a differential element to a parallel rectangle, taken over four quadrants).
export function viewToSquare(a, h) {
  const A = a / 2 / h, B = A, sa = Math.sqrt(1 + A * A), sb = Math.sqrt(1 + B * B);
  return (2 / Math.PI) * ((A / sa) * Math.atan(B / sa) + (B / sb) * Math.atan(A / sb));
}
// Wells's shelter (Essay on Dew, 1814, p. 121): a cambric handkerchief on four sticks, 6 inches above
// the grass, sides 2 feet. The grass under its middle sees the cloth over this share of its sky:
export const WELLS_COVER = viewToSquare(24, 6);   // inches; about 0.83

// Two surfaces in balance together: the cloth (top sees the sky, underside sees the grass beneath,
// air on both faces) and the sheltered grass (sees the cloth over `cover` of its sky, open sky over the rest).
// Simplifications, named: the cloth is opaque to infrared, the wind under it is the same as outside,
// and the cold air draining from the exposed grass that Wells himself mentions is left out.
export function balanceSheltered({ dw, ta, rh, u10, p = 1000 }, { eps = 0.98, k = 1, z = 0.5, cover = WELLS_COVER } = {}) {
  const h = hConv(windAt(u10, z), k), ea = (rh / 100) * esWater(ta), qa = q(ea, p);
  const latent = (t) => { const es = t >= 0 ? esWater(t) : esIce(t); return (t >= 0 ? LV : LS) * Math.max(0, (h / CP) * (qa - q(es, p))); };
  const E = (t) => eps * SIGMA * (t + 273.15) ** 4;
  const solve = (f, lo, hi) => { for (let i = 0; i < 60; i++) { const m = (lo + hi) / 2; if (f(m) > 0) lo = m; else hi = m; } return (lo + hi) / 2; };
  let tg = ta, th = ta;
  for (let it = 0; it < 60; it++) {                        // alternate the two balances until the grass settles
    th = solve(t => eps * dw - E(t) + E(tg) - E(t) + 2 * h * (ta - t) + latent(t), ta - 40, ta + 5);
    const next = solve(t => eps * ((1 - cover) * dw) + cover * E(th) - E(t) + h * (ta - t) + latent(t), ta - 40, ta + 5);
    const done = Math.abs(next - tg) < 1e-6; tg = next; if (done) break;
  }
  const es = tg >= 0 ? esWater(tg) : esIce(tg);
  return { ts: tg, cloth: th, cond: Math.max(0, (h / CP) * (qa - q(es, p))) };
}
