// Run on your server with Node.js 22 or newer.
// Install: npm install cosmicephemeris@0.5.0
// Configure COSMICEPHEMERIS_KEY privately, then run: node birth-chart.mjs
import { writeFile } from "node:fs/promises";
import { CosmicEphemeris, CosmicEphemerisError } from "cosmicephemeris";

try {
  // Reads COSMICEPHEMERIS_KEY from the server environment.
  const api = new CosmicEphemeris();
  const chart = await api.natalSvg({
    // Synthetic example, not a real person's birth record.
    birth: {
      date: "1990-01-01",
      time: "12:00",
      timezone: "America/New_York",
      lat: 40.7128,
      lon: -74.006,
    },
    zodiac: "tropical",
    house_system: "equal",
    theme: "dark",
    show_aspects: true,
  });

  // The SVG is a top-level field in the response.
  // "wx" avoids overwriting an existing chart; 0600 keeps the file private.
  await writeFile("birth-chart.svg", chart.svg, {
    encoding: "utf8", flag: "wx", mode: 0o600,
  });
  console.log("Created birth-chart.svg. Open it in your browser.");
} catch (error) {
  if (error instanceof CosmicEphemerisError) {
    // SDK errors expose sanitized fields. Do not log credentials or payloads.
    console.error("Chart request failed:", error.code, error.status ?? "");
  } else if (error?.code === "EEXIST") {
    console.error("birth-chart.svg already exists. Rename it before running again.");
  } else {
    console.error("Could not save the chart. Check your folder permissions.");
  }
  process.exitCode = 1;
}
