import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";

const componentRoot = join(import.meta.dir, "..");
const outFile = join(componentRoot, "public", "app.js");

const result = await Bun.build({
  entrypoints: [join(componentRoot, "src", "app.tsx")],
  target: "browser",
  format: "iife",
  define: {
    "process.env.NODE_ENV": "\"production\"",
    "import.meta.env": "{\"MODE\":\"production\"}",
    "import.meta.env.MODE": "\"production\"",
  },
  minify: true,
  sourcemap: "none",
});

if (!result.success || result.outputs.length === 0) {
  const messages = result.logs.map((item) => item.message).join("; ");
  throw new Error(`frontend app build failed: ${messages || "no output"}`);
}

const bundle = await result.outputs[0].text();
mkdirSync(dirname(outFile), { recursive: true });
writeFileSync(outFile, bundle, "utf8");

console.log(JSON.stringify({ ok: true, outFile, bytes: Buffer.byteLength(bundle, "utf8") }));
