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

const binDir = path.dirname(fileURLToPath(import.meta.url));
const tsEntrypoint = path.join(binDir, "hwlab-cli.ts");
const repoRoot = path.resolve(binDir, "../../..");
const runBun = path.join(repoRoot, "scripts/run-bun.mjs");
const command = process.env.HWLAB_BUN_COMMAND || process.execPath;
const args = process.env.HWLAB_BUN_COMMAND
  ? [tsEntrypoint, ...process.argv.slice(2)]
  : [runBun, tsEntrypoint, ...process.argv.slice(2)];
const child = spawn(command, args, { stdio: "inherit", env: process.env, cwd: repoRoot });

child.on("error", (error) => {
  process.stderr.write(JSON.stringify({ ok: false, cli: "hwlab-cli", status: "failed", error: { code: "bun_spawn_failed", message: error.message } }, null, 2) + "\n");
  process.exit(127);
});
child.on("exit", (code, signal) => {
  if (signal) process.kill(process.pid, signal);
  else process.exit(code ?? 0);
});
