#!/usr/bin/env node
/**
 * Install QwenClaw Agent for Qwen Code CLI
 * 
 * This installs QwenClaw as a Qwen Code CLI agent/plugin
 * that is ALWAYS ON by default.
 * 
 * Usage: bun run install-agent.js
 */

import { join } from "path";
import { existsSync, readFileSync, writeFile, mkdirSync, cpSync } from "fs";

const QWEN_DIR = join(process.env.HOME || process.env.USERPROFILE || "", ".qwen");
const QWEN_AGENTS_DIR = join(QWEN_DIR, "agents");
const QWENCLAW_DIR = process.env.QWENCLAW_DIR || join(process.env.HOME || process.env.USERPROFILE || "", "qwenclaw");
const AGENT_SOURCE = join(QWENCLAW_DIR, "qwen-agent");
const AGENT_DEST = join(QWEN_AGENTS_DIR, "qwenclaw");

const COLORS = {
  cyan: "\x1b[36m",
  green: "\x1b[32m",
  yellow: "\x1b[33m",
  red: "\x1b[31m",
  magenta: "\x1b[35m",
  bold: "\x1b[1m",
  reset: "\x1b[0m",
};

function log(message, color = "reset") {
  console.log(`${COLORS[color]}${message}${COLORS.reset}`);
}

function showBanner() {
  log("\n" + "═".repeat(60), "cyan");
  log("  🐾 INSTALL QWENCLAW AGENT FOR QWEN CODE CLI", "cyan");
  log("═".repeat(60), "cyan");
}

/**
 * Ensure directories exist
 */
function ensureDirs() {
  log("\n📁 Checking directories...", "cyan");

  if (!existsSync(QWEN_DIR)) {
    mkdirSync(QWEN_DIR, { recursive: true });
    log("✅ Created Qwen directory", "green");
  }

  if (!existsSync(QWEN_AGENTS_DIR)) {
    mkdirSync(QWEN_AGENTS_DIR, { recursive: true });
    log("✅ Created agents directory", "green");
  }

  if (!existsSync(AGENT_SOURCE)) {
    log(`❌ Agent source not found: ${AGENT_SOURCE}`, "red");
    log("   Please ensure QwenClaw is installed", "yellow");
    process.exit(1);
  }
}

/**
 * Copy agent files
 */
function installAgent() {
  log("\n📦 Installing QwenClaw agent...", "cyan");

  try {
    if (existsSync(AGENT_DEST)) {
      log("   Removing old agent installation...", "yellow");
      import("fs").then(({ rmSync }) => {
        rmSync(AGENT_DEST, { recursive: true, force: true });
      });
    }

    cpSync(AGENT_SOURCE, AGENT_DEST, { recursive: true });
    log("✅ Agent installed to: " + AGENT_DEST, "green");
  } catch (err) {
    log(`❌ Failed to install agent: ${err.message}`, "red");
  }
}

/**
 * Update Qwen Code CLI config
 */
function updateConfig() {
  log("\n⚙️  Updating Qwen Code CLI config...", "cyan");

  const configFile = join(QWEN_DIR, "config.json");
  let config = {};

  if (existsSync(configFile)) {
    try {
      config = JSON.parse(readFileSync(configFile, "utf-8"));
      log("✅ Loaded existing config", "green");
    } catch {
      log("⚠️  Could not parse existing config", "yellow");
    }
  }

  // Enable QwenClaw agent
  if (!config.agents) {
    config.agents = {};
  }

  config.agents.default = "qwenclaw";
  config.agents.enabled = ["qwenclaw"];
  config.agents.autoStart = true;

  // Enable skills
  if (!config.skills) {
    config.skills = {};
  }

  config.skills.default = "qwenclaw-integration";
  config.skills.enabled = [
    "qwenclaw-integration",
    "gui-automation",
    "qwenbot-integration",
  ];

  // Save config
  try {
    writeFile(configFile, JSON.stringify(config, null, 2) + "\n", "utf-8");
    log("✅ Qwen Code CLI config updated", "green");
  } catch (err) {
    log(`❌ Failed to save config: ${err.message}`, "red");
  }
}

/**
 * Show completion message
 */
function showCompletion() {
  log("\n" + "═".repeat(60), "cyan");
  log("  ✅ QWENCLAW AGENT INSTALLED!", "green");
  log("═".repeat(60), "cyan");

  log("\n📌 Installation Summary:", "yellow");
  log("   • Agent Location: " + AGENT_DEST, "cyan");
  log("   • Default Agent: qwenclaw", "cyan");
  log("   • Auto-Start: enabled", "cyan");
  log("   • Skills: 3 enabled", "cyan");

  log("\n🎯 Usage in Qwen Code CLI:", "yellow");
  log("   /qwenclaw start     - Start daemon", "cyan");
  log("   /qwenclaw status    - Check status", "cyan");
  log("   /qwenclaw send      - Send message", "cyan");
  log("   /qwenclaw help      - Show help", "cyan");

  log("\n🌐 Web Dashboard: http://127.0.0.1:4632", "cyan");
  log("\n📖 Restart Qwen Code CLI for changes to take effect", "yellow");
  log("\n");
}

/**
 * Main installation
 */
async function main() {
  showBanner();

  try {
    ensureDirs();
    installAgent();
    updateConfig();
    showCompletion();
  } catch (err) {
    log(`\n❌ Installation failed: ${err.message}`, "red");
    process.exit(1);
  }
}

main();
