#!/usr/bin/env node
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import os from "node:os";
import path from "node:path";

const args = process.argv.slice(2);

if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
  process.stdout.write(JSON.stringify({
    script: "run-bun",
    usage: "node scripts/run-bun.mjs <bun-args...>",
    env: "HWLAB_BUN_COMMAND",
    resolvedCommand: resolveBunCommand()
  }, null, 2) + "\n");
  process.exit(0);
}

const command = resolveBunCommand();
if (!command) {
  process.stderr.write(JSON.stringify({
    script: "run-bun",
    status: "failed",
    error: "bun_command_not_found",
    checked: bunCandidates()
  }, null, 2) + "\n");
  process.exit(127);
}

const child = spawn(command, args, {
  cwd: process.cwd(),
  env: process.env,
  stdio: "inherit"
});

child.on("error", (error) => {
  process.stderr.write(JSON.stringify({
    script: "run-bun",
    status: "failed",
    error: "bun_spawn_failed",
    command,
    reason: error.message
  }, null, 2) + "\n");
  process.exit(127);
});

child.on("exit", (code, signal) => {
  if (signal) {
    try {
      process.kill(process.pid, signal);
    } catch (error) {
      process.stderr.write(JSON.stringify({
        script: "run-bun",
        status: "failed",
        error: "bun_child_signal_forward_failed",
        signal,
        reason: error?.message ?? String(error)
      }, null, 2) + "\n");
      process.exit(128);
    }
    return;
  }
  process.exit(code ?? 0);
});

function resolveBunCommand() {
  for (const candidate of bunCandidates()) {
    if (!candidate) continue;
    if (!candidate.includes(path.sep)) return candidate;
    if (existsSync(candidate)) return candidate;
  }
  return null;
}

function bunCandidates() {
  return [
    process.env.HWLAB_BUN_COMMAND,
    path.join(process.cwd(), "node_modules", ".bin", process.platform === "win32" ? "bun.exe" : "bun"),
    path.join(os.homedir(), ".bun", "bin", process.platform === "win32" ? "bun.exe" : "bun"),
    "/root/.bun/bin/bun",
    "/usr/local/bin/bun",
    "bun"
  ].filter(Boolean);
}
