import { spawnSync } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import {
  buildProductionConfig,
  resolveProductionInventory,
  wranglerInvocation,
} from "./cloudflare-production-config.mjs";

const projectDirectory = fileURLToPath(new URL("../", import.meta.url));

function runWrangler(arguments_) {
  const invocation = wranglerInvocation({
    execPath: process.execPath,
    projectDirectory,
    arguments_,
  });
  const result = spawnSync(invocation.command, invocation.arguments, {
    cwd: projectDirectory,
    encoding: "utf8",
    stdio: ["ignore", "pipe", "pipe"],
  });

  if (result.error || result.status !== 0) {
    throw new Error("Cloudflare inventory lookup failed. Check the active Wrangler login.");
  }

  return result.stdout;
}

const inventory = resolveProductionInventory({
  d1Json: runWrangler(["d1", "list", "--json"]),
  r2Text: runWrangler(["r2", "bucket", "list"]),
});
const config = buildProductionConfig(inventory);
const outputPath = new URL("../wrangler.production.jsonc", import.meta.url);

await writeFile(outputPath, `${JSON.stringify(config, null, 2)}\n`, "utf8");
console.log("Wrote isolated HearBooks production configuration.");
