import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";

const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const packageJson = JSON.parse(
  readFileSync(path.join(rootDir, "package.json"), "utf8"),
);

let buildNumber =
  process.env.BUILD_NUMBER || process.env.VITE_BUILD_NUMBER || "dev";
try {
  const buildInfo = JSON.parse(
    readFileSync(path.join(rootDir, "src/buildInfo.json"), "utf8"),
  );
  buildNumber = buildInfo.buildNumber ?? buildNumber;
} catch {}

const outputDir = path.join(rootDir, "app_dist/linux");
const outputFile = path.join(outputDir, "farmcontrol-server");

await Bun.$`mkdir -p ${outputDir}`;

const result = await Bun.build({
  entrypoints: [path.join(rootDir, "src/headless.js")],
  outdir: path.join(rootDir, "build/linux-bundle"),
  target: "bun",
  format: "esm",
  external: [
    "canvas",
    "@napi-rs/canvas",
    "@img/*",
    "@napi-rs/*",
  ],
  define: {
    "process.env.FC_PACKAGE_VERSION": JSON.stringify(packageJson.version),
    "process.env.FC_BUILD_NUMBER": JSON.stringify(buildNumber),
  },
});

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

const compileResult = Bun.spawn([
  "bun",
  "build",
  "--compile",
  "--target=bun-linux-x64",
  path.join(rootDir, "build/linux-bundle/headless.js"),
  "--outfile",
  outputFile,
], {
  cwd: rootDir,
  stdout: "inherit",
  stderr: "inherit",
});

const exitCode = await compileResult.exited;
if (exitCode !== 0) {
  process.exit(exitCode);
}

console.log(`Linux binary written to ${outputFile}`);
