import { rm } from "node:fs/promises";
import { join } from "node:path";

import { buildDir, cleanup, codeGeneration, projectRoot, viteBuild } from "./build-common";

const executablePath = join(projectRoot, "dist/dial-server");

async function build() {
  try {
    await viteBuild();
    await codeGeneration();
    await bunCompile();
    await cleanup();
    console.log(`Built executable: ${executablePath}`);
  } catch (error) {
    await cleanup();
    console.error("Build failed:", error);
    process.exit(1);
  }
}

async function bunCompile() {
  console.log("Step 3/3: Bun compile...");
  await rm(executablePath, { force: true });

  const target = process.env["BUN_TARGET"] ?? process.env["BUILD_TARGET"];
  const result = await Bun.build({
    compile: target
      ? {
          autoloadBunfig: true,
          autoloadDotenv: true,
          outfile: executablePath,
          target: target as Bun.Build.CompileTarget,
        }
      : {
          autoloadBunfig: true,
          autoloadDotenv: true,
          outfile: executablePath,
        },
    entrypoints: [join(buildDir, "server-entry.ts")],
    minify: true,
    sourcemap: "linked",
  });

  if (!result.success) {
    console.error("Bun compile failed:", result.logs);
    await cleanup();
    process.exit(1);
  }
}

await build();
