import { cleanupPidFile } from "../pid";
import { unlink } from "fs/promises";
import { join } from "path";

const QWEN_DIR = join(process.cwd(), ".qwen");
const HEARTBEAT_DIR = join(QWEN_DIR, "qwenclaw");
const STATE_FILE = join(HEARTBEAT_DIR, "state.json");
const SESSION_FILE = join(HEARTBEAT_DIR, "session.json");

export async function stop(): Promise<void> {
  const pidFile = join(HEARTBEAT_DIR, "daemon.pid");
  let raw: string;
  try {
    raw = (await Bun.file(pidFile).text()).trim();
  } catch {
    console.log("QwenClaw daemon is not running (no PID file found).");
    return;
  }

  const pid = Number(raw);
  if (!pid || isNaN(pid)) {
    console.log("QwenClaw daemon is not running (invalid PID file).");
    await cleanupPidFile();
    return;
  }

  try {
    process.kill(pid, "SIGTERM");
    console.log(`QwenClaw daemon (PID ${pid}) stopped.`);
  } catch (err) {
    console.log(`Failed to stop daemon (PID ${pid}): ${err instanceof Error ? err.message : err}`);
  }

  await cleanupPidFile();
  await unlink(STATE_FILE).catch(() => {});
}

export async function stopAll(): Promise<void> {
  // Stop all daemon processes by finding and killing them
  console.log("Stopping all QwenClaw daemons...");
  await stop();
}

export async function clear(): Promise<void> {
  await cleanupPidFile();
  await unlink(STATE_FILE).catch(() => {});
  await unlink(SESSION_FILE).catch(() => {});
  console.log("QwenClaw state cleared.");
}
