import fs from "fs";
import path from "path";
import axios from "axios";

// Single config point
const config = { schemaUrl: "/api/schema/", baseUrl: "/api/" };

async function main() {
  const outDir = path.resolve("./src/openapi");
  const outFile = path.join(outDir, "schema.json");
  const base = process.env.VITE_API_BASE_URL || "http://localhost:8000";
  const url = new URL(config.schemaUrl, base).toString();

  console.log(`[openapi] Fetching schema from ${url}`);
  const res = await axios.get(url, { headers: { Accept: "application/json" } });

  await fs.promises.mkdir(outDir, { recursive: true });
  await fs.promises.writeFile(outFile, JSON.stringify(res.data, null, 2), "utf8");
  console.log(`[openapi] Wrote ${outFile}`);
}

main().catch((err) => {
  console.error("[openapi] Failed to fetch schema:", err?.message || err);
  process.exit(1);
});
