import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { basename, join } from "node:path";

const outdir = join(process.cwd(), "templates", "aspect-runtime");
await mkdir(outdir, { recursive: true });

const result = await Bun.build({
  entrypoints: [join(process.cwd(), "src", "aspect-runtime", "index.ts")],
  outdir,
  naming: "aspectRunnerSdk.js",
  target: "node",
  format: "esm",
  external: [
    "remark-gfm",
    "remark-mdx",
    "remark-parse",
    "remark-stringify",
    "typescript",
    "unified",
  ],
});

if (!result.success) {
  for (const log of result.logs) {
    console.error(log);
  }
  process.exit(1);
}

for (const output of result.outputs) {
  console.log(`  ${basename(output.path)}  ${(output.size / 1024).toFixed(1)} KB`);
}

const target = join(outdir, "aspectRunnerSdk.js");
if (!existsSync(target)) {
  throw new Error(`aspect runtime build did not emit ${target}`);
}

let content = await readFile(target, "utf8");
content = [
  "/* Generated by packages/context-cli/scripts/build-aspect-runtime.ts. Do not edit directly. */",
  content,
].join("\n");
await writeFile(target, content);
