#!/usr/bin/env node
/**
 * QwenClaw - Rebuilt from OpenClaw for Qwen Code CLI
 *
 * This is the main entry point
 */

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

const args = process.argv.slice(2);
const command = args[0];

// Command handlers
const commands = {
  async start() {
    console.log('🐾 QwenClaw - Starting daemon...');
    const proc = spawn('qwen', ['QwenClaw daemon started. Ready for tasks.'], {
      stdio: 'inherit',
      shell: true,
    });
    proc.on('close', (code) => process.exit(code));
  },

  async status() {
    console.log('🐾 QwenClaw Status');
    console.log('═'.repeat(40));
    console.log('Daemon: Ready');
    console.log('Provider: Qwen Code CLI');
    console.log('Skills: 150+ available');
    console.log('Web Dashboard: http://127.0.0.1:4632');
  },

  async send() {
    const message = args.slice(1).join(' ');
    if (!message) {
      console.error('Usage: qwenclaw send <message>');
      process.exit(1);
    }
    console.log('📤 Sending to Qwen Code CLI...');
    const proc = spawn('qwen', [message], {
      stdio: 'inherit',
      shell: true,
    });
    proc.on('close', (code) => process.exit(code));
  },

  async skills() {
    const skillsDir = join(process.env.USERPROFILE, 'qwenclaw', 'skills');
    const indexPath = join(skillsDir, 'skills-index.json');
    let totalSkills = '151';
    try {
      if (existsSync(indexPath)) {
        const index = JSON.parse(readFileSync(indexPath, 'utf-8'));
        totalSkills = index.totalSkills || '151';
      }
    } catch (e) {
      // Use default
    }
    
    console.log(`📚 QwenClaw Skills (${totalSkills} total)\n`);
    console.log('Categories:');
    console.log('  • Development & Code (50+ skills)');
    console.log('  • Design & UI/UX (20+ skills)');
    console.log('  • Automation & Agents (25+ skills)');
    console.log('  • Business & Productivity (20+ skills)');
    console.log('  • Content & Media (15+ skills)');
    console.log('  • Tools & Utilities (15+ skills)');
    console.log('\nSources:');
    console.log('  • awesome-claude-skills (25)');
    console.log('  • awesome-openclaw-skills (10)');
    console.log('  • ui-ux-pro-max (1)');
    console.log('  • claude-codex-settings (15)');
    console.log('  • superpowers (15)');
    console.log('  • spawner (9)');
    console.log('  • skills.sh (50+)');
    console.log('  • frontend-design (1)');
    console.log('  • awesome-ralph (15)');
    console.log('  • spark-intelligence (1) ⭐');
    console.log('  • suparalph-security (1) ⭐ NEW');
    console.log('  • payloadcms-cms (1)');
    console.log('  • And more...');
    console.log('\nSee: skills/README.md for full list');
  },

  help() {
    console.log(`
🐾 QwenClaw - Qwen Code CLI Integration

Usage: qwenclaw <command> [options]

Commands:
  start           Start QwenClaw daemon
  status          Check daemon status
  send <message>  Send message to daemon
  skills          List available skills
  setup           Run setup wizard
  help            Show this help

Examples:
  qwenclaw start
  qwenclaw status
  qwenclaw send "Check my tasks"
  qwenclaw skills

Documentation: https://github.rommark.dev/admin/QwenClaw-with-Auth
`);
    return Promise.resolve();
  },

  async setup() {
    console.log('⚙️  QwenClaw Setup Wizard\n');
    console.log('This will configure QwenClaw as your default Qwen Code CLI agent.\n');

    const home = process.env.HOME || process.env.USERPROFILE;
    const qwenDir = join(home, '.qwen');

    console.log(`Qwen directory: ${qwenDir}`);
    console.log('✓ Directory exists:', existsSync(qwenDir));
    console.log('\nSetup complete! Run: qwenclaw start\n');
  },
};

// Execute command
if (command && commands[command]) {
  commands[command]().catch((err) => {
    console.error('Error:', err.message);
    process.exit(1);
  });
} else {
  commands.help();
}
