#!/usr/bin/env bun

import solidPlugin from "./node_modules/@opentui/solid/scripts/solid-plugin";
import fs from "fs";

const version = process.env.OPENCODE_VERSION!;
const channel = process.env.OPENCODE_CHANNEL!;

const result = await Bun.build({
  target: "bun",
  outdir: "./dist",
  entrypoints: ["./src/index.ts", "./src/cli/cmd/tui/worker.ts"],
  plugins: [solidPlugin],
  naming: {
    entry: "[dir]/[name].js",
  },
  define: {
    OPENCODE_VERSION: JSON.stringify(version),
    OPENCODE_CHANNEL: JSON.stringify(channel),
  },
  external: ["@opentui/core-*"],
});

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

// Move worker file to worker.ts at the dist root so the code can find it
if (fs.existsSync("./dist/cli/cmd/tui/worker.js")) {
  fs.renameSync("./dist/cli/cmd/tui/worker.js", "./dist/worker.ts");
  fs.rmdirSync("./dist/cli/cmd/tui", { recursive: true });
}
