import { readFile } from "fs/promises";
import { join } from "path";
import { checkExistingDaemon } from "../pid";

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

export async function status(): Promise<void> {
  const existingPid = await checkExistingDaemon();

  if (!existingPid) {
    console.log("QwenClaw daemon is not running.");
  } else {
    console.log(`QwenClaw daemon is running (PID ${existingPid}).`);
  }

  try {
    const state = await Bun.file(STATE_FILE).json();
    console.log("\nState:");
    if (state.heartbeat) {
      const ms = state.heartbeat.nextAt - Date.now();
      const s = Math.floor(ms / 1000);
      const h = Math.floor(s / 3600);
      const m = Math.floor((s % 3600) / 60);
      if (h > 0) {
        console.log(`  Heartbeat: in ${h}h ${m}m`);
      } else if (m > 0) {
        console.log(`  Heartbeat: in ${m}m`);
      } else {
        console.log(`  Heartbeat: in ${s % 60}s`);
      }
    } else {
      console.log("  Heartbeat: disabled");
    }

    if (state.jobs && state.jobs.length > 0) {
      console.log(`  Jobs: ${state.jobs.length}`);
      for (const job of state.jobs) {
        const ms = job.nextAt - Date.now();
        const s = Math.floor(ms / 1000);
        const h = Math.floor(s / 3600);
        const m = Math.floor((s % 3600) / 60);
        if (h > 0) {
          console.log(`    - ${job.name}: in ${h}h ${m}m`);
        } else if (m > 0) {
          console.log(`    - ${job.name}: in ${m}m`);
        } else {
          console.log(`    - ${job.name}: in ${s % 60}s`);
        }
      }
    } else {
      console.log("  Jobs: none");
    }

    console.log(`  Security: ${state.security || "unknown"}`);
    console.log(`  Telegram: ${state.telegram ? "enabled" : "disabled"}`);
    console.log(`  Web UI: ${state.web?.enabled ? `http://${state.web.host}:${state.web.port}` : "disabled"}`);
  } catch {
    console.log("  State: not available");
  }

  try {
    const session = await Bun.file(SESSION_FILE).json();
    console.log(`\nSession: ${session.sessionId?.slice(0, 8) || "none"}...`);
  } catch {
    console.log("\nSession: none");
  }
}
