/**
 * QwenClaw Command Handler for Qwen Code CLI
 */

import { spawn } from "child_process";
import { join } from "path";
import { existsSync, readFileSync } from "fs";

const QWENCLAW_DIR = process.env.QWENCLAW_DIR || join(process.env.HOME || process.env.USERPROFILE || "", "qwenclaw");
const PID_FILE = join(process.env.HOME || process.env.USERPROFILE || "", ".qwen", "qwenclaw", "daemon.pid");

function isRunning() {
  if (!existsSync(PID_FILE)) return false;
  try {
    const pid = parseInt(readFileSync(PID_FILE, "utf-8").trim(), 10);
    if (isNaN(pid)) return false;
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

export async function handle(args) {
  const command = args[0];
  
  switch (command) {
    case "start":
      if (isRunning()) {
        return "✅ QwenClaw daemon is already running";
      }
      
      const proc = spawn("bun", ["run", "start", "--web"], {
        cwd: QWENCLAW_DIR,
        detached: true,
        stdio: "ignore",
        windowsHide: true,
      });
      
      proc.unref();
      
      return "🚀 Starting QwenClaw daemon...\n   Web Dashboard: http://127.0.0.1:4632";
    
    case "status":
      if (isRunning()) {
        const pid = parseInt(readFileSync(PID_FILE, "utf-8").trim(), 10);
        return `✅ QwenClaw daemon is running\n   PID: ${pid}\n   Web Dashboard: http://127.0.0.1:4632`;
      }
      return "❌ QwenClaw daemon is not running\n   Run: /qwenclaw start";
    
    case "send":
      const message = args.slice(1).join(" ");
      if (!message) return "Usage: /qwenclaw send <message>";
      
      return new Promise((resolve) => {
        const proc = spawn("bun", ["run", "send", message], {
          cwd: QWENCLAW_DIR,
          stdio: ["pipe", "pipe", "pipe"],
        });
        
        let output = "";
        proc.stdout.on("data", (data) => {
          output += data.toString();
        });
        
        proc.on("close", () => {
          resolve(output || "Message sent to daemon");
        });
      });
    
    case "skills":
      return `
QwenClaw Skills (79 total):
  • qwenclaw-integration - Daemon control & communication
  • gui-automation - Full browser automation with Playwright
  • qwenbot-integration - QwenBot AI assistant
  • shadcn-ui-design - shadcn/ui design patterns
  • metatrader5-trading - MetaTrader 5 trading
  • ... and 74 more

Run: qwenclaw skills (in terminal) for full list
`;
    
    case "help":
    default:
      return `
🐾 QwenClaw - Your Always-ON AI Assistant

Commands:
  /qwenclaw start     - Start daemon
  /qwenclaw status    - Check status  
  /qwenclaw send      - Send message
  /qwenclaw skills    - List skills
  /qwenclaw help      - This help

Terminal Commands:
  qwenclaw start --web
  qwenclaw status
  qwenclaw send "message"
  qwenclaw skills

Web Dashboard: http://127.0.0.1:4632
`;
  }
}
