// Download SURFRAD daily files from NOAA GML into a cache directory, skipping ones already there.
// Data: NOAA GML SURFRAD, CC0 1.0 (README_SURFRAD.txt). https://gml.noaa.gov/aftp/data/radiation/surfrad/
import fs from 'node:fs'; import path from 'node:path';
export const STATIONS = { bon: 'Bondville_IL', dra: 'Desert_Rock_NV' };
const BASE = 'https://gml.noaa.gov/aftp/data/radiation/surfrad';
export const fileName = (st, year, jday) => `${st}${String(year).slice(2)}${String(jday).padStart(3, '0')}.dat`;
export async function ensure(st, year, jdays, cache, log = () => {}) {
  const dir = path.join(cache, st); fs.mkdirSync(dir, { recursive: true });
  const out = [];
  for (const j of jdays) {
    const f = fileName(st, year, j), p = path.join(dir, f);
    if (!fs.existsSync(p) || fs.statSync(p).size === 0) {
      let ok = false;
      for (let a = 0; a < 5 && !ok; a++) {
        try { const r = await fetch(`${BASE}/${STATIONS[st]}/${year}/${f}`); if (!r.ok) throw new Error(r.status);
          fs.writeFileSync(p, Buffer.from(await r.arrayBuffer())); ok = true; }
        catch (e) { await new Promise(res => setTimeout(res, 2000 * (a + 1))); }
      }
      if (!ok) throw new Error(`could not fetch ${f}`);
      log(`fetched ${f}`);
    }
    out.push(p);
  }
  return out;
}
