import { mkdirSync, openSync, readFileSync, rmSync } from "node:fs";
import { resolve } from "node:path";

const action = process.argv[2];
const root = process.cwd();
const stateDir = resolve(root, ".state/caserun-native");
const pidPath = resolve(stateDir, "server.pid");
const logPath = resolve(stateDir, "server.log");

function readPid(): number | null {
  try {
    const pid = Number(readFileSync(pidPath, "utf8").trim());
    return Number.isInteger(pid) && pid > 0 ? pid : null;
  } catch {
    return null;
  }
}

function isRunning(pid: number | null): boolean {
  if (!pid) return false;
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

async function waitForExit(pid: number): Promise<boolean> {
  const deadline = Date.now() + 5000;
  while (Date.now() < deadline) {
    if (!isRunning(pid)) return true;
    await Bun.sleep(25);
  }
  return !isRunning(pid);
}

mkdirSync(stateDir, { recursive: true });
const pid = readPid();

if (action === "start") {
  if (isRunning(pid)) {
    console.log(JSON.stringify({ ok: true, action, status: "already-running", pid, logPath }));
    process.exit(0);
  }
  rmSync(pidPath, { force: true });
  const logFd = openSync(logPath, "a");
  const child = Bun.spawn([process.execPath, "scripts/caserun-native-supervisor.ts"], { cwd: root, stdin: "ignore", stdout: logFd, stderr: logFd });
  child.unref();
  await Bun.write(pidPath, `${child.pid}\n`);
  console.log(JSON.stringify({ ok: true, action, status: "started", pid: child.pid, logPath }));
} else if (action === "stop") {
  if (!isRunning(pid)) {
    rmSync(pidPath, { force: true });
    console.log(JSON.stringify({ ok: true, action, status: "stopped" }));
  } else {
    process.kill(pid!, "SIGTERM");
    if (!await waitForExit(pid!)) {
      console.error(JSON.stringify({ ok: false, action, status: "stop-timeout", pid }));
      process.exit(1);
    }
    rmSync(pidPath, { force: true });
    console.log(JSON.stringify({ ok: true, action, status: "stopped", pid }));
  }
} else if (action === "status") {
  const running = isRunning(pid);
  console.log(JSON.stringify({ ok: running, action, status: running ? "running" : "stopped", pid: running ? pid : null, logPath }));
  process.exit(running ? 0 : 1);
} else if (action === "logs") {
  const lines = readFileSync(logPath, "utf8").trimEnd().split("\n").slice(-80);
  console.log(lines.join("\n"));
} else {
  console.error("usage: bun run scripts/caserun-native-service.ts <start|stop|status|logs>");
  process.exit(2);
}
