#!/usr/bin/env node
/**
 * QwenClaw Startup Hook for Qwen Code
 * This script is called when Qwen Code starts
 * It ensures the QwenClaw daemon is running
 */

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

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

function log(message) {
  console.log(`[QwenClaw] ${message}`);
}

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

function startDaemon() {
  if (isDaemonRunning()) {
    log("Daemon already running, skipping auto-start");
    return;
  }
  
  log("Auto-starting QwenClaw daemon...");
  
  try {
    const child = spawn("bun", ["run", "start", "--web"], {
      cwd: QWENCLAW_DIR,
      detached: true,
      stdio: "ignore",
      windowsHide: true,
    });
    
    child.unref();
    log(`Daemon started (PID: ${child.pid})`);
  } catch (err) {
    log(`Failed to start daemon: ${err.message}`);
  }
}

// Check if auto-start is enabled in settings
function isAutoStartEnabled() {
  if (!existsSync(SETTINGS_FILE)) return true; // Default to enabled
  
  try {
    const settings = JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
    return settings.autoStart !== false; // Default to true
  } catch {
    return true;
  }
}

// Main
if (isAutoStartEnabled()) {
  // Delay slightly to not block Qwen Code startup
  setTimeout(startDaemon, 2000);
}
