// Node.js 22+; server-side only. Install: npm install cosmicephemeris@0.5.0
// Set COSMICEPHEMERIS_KEY privately. No automatic retries.
import { mkdir, writeFile } from "node:fs/promises";
import { CosmicEphemeris, CosmicEphemerisError } from "cosmicephemeris";

const output = "moon-calendar-output";
try {
  const api = new CosmicEphemeris();
  // Reserve a new private folder before making a metered call.
  await mkdir(output, { mode: 0o700 });
  const calendar = await api.moonPhases({
    mode: "calendar",
    start: { date: "2026-11-01", time: "00:00", timezone: "UTC" },
    end: { date: "2026-12-01", time: "00:00", timezone: "UTC" },
    display_timezone: "UTC",
    include_ical: true,
  });
  await writeFile(`${output}/moon-phases.json`, JSON.stringify(calendar, null, 2), {
    encoding: "utf8", flag: "wx", mode: 0o600,
  });
  if (calendar.result.ical !== null) {
    // Preserve the returned CRLF line endings. Do not save JSON as .ics.
    await writeFile(`${output}/moon-phases.ics`, calendar.result.ical, {
      encoding: "utf8", flag: "wx", mode: 0o600,
    });
    console.log("Created moon-calendar-output/moon-phases.ics and moon-phases.json.");
  } else {
    console.log("No phase events in this interval; saved JSON only.");
  }
} catch (error) {
  if (error instanceof CosmicEphemerisError) {
    console.error("API request failed:", error.code, error.status ?? "");
  } else if (error?.code === "EEXIST") {
    console.error("Output folder already exists. Rename it before another run.");
  } else {
    console.error("Could not finish. Check the input and folder permissions.");
  }
  process.exitCode = 1;
}
