#!/usr/bin/env node

/**
 * ============================================================================
 * MyClaw Start - 智能启动（图标 & 命令行通用入口）
 * ============================================================================
 *
 * 使用: myclaw start
 *
 * Windows 流程:
 *   1. 检查 WSL → 未装则引导安装
 *   2. 检查 OpenClaw 发行版 → 未装则引导安装
 *   3. 检查 Gateway → 未启动则 update + launch（新窗口）
 *   4. 打开浏览器
 *
 * Linux/Mac 流程:
 *   等同于 myclaw launch（update + patch + gateway + open）
 * ============================================================================
 */

const { execSync } = require('child_process');
const os = require('os');
const path = require('path');

const isWindows = os.platform() === 'win32';
const C = isWindows
  ? { r: '', g: '', y: '', b: '', nc: '' }
  : { r: '\x1b[31m', g: '\x1b[32m', y: '\x1b[33m', b: '\x1b[34m', nc: '\x1b[0m' };

const BAR = '============================================';

// ============================================================================
// Windows 启动流程
// ============================================================================

function startWindows() {
  // Step 1: 检查 WSL
  console.log('[1/4] WSL...');
  try {
    execSync('wsl --version', { stdio: 'pipe', timeout: 10000 });
    console.log('      ' + C.g + '[OK]' + C.nc);
  } catch {
    console.log('      ' + C.r + '[未安装]' + C.nc);
    console.log('');
    console.log('正在启动 WSL2 安装向导...');
    try { execSync('myclaw wsl2', { stdio: 'inherit' }); } catch {}
    console.log('');
    console.log('请 ' + C.y + '重启电脑' + C.nc + ' 后再次双击图标');
    return;
  }
  console.log('');

  // Step 2: 检查 OpenClaw 发行版
  console.log('[2/4] OpenClaw Linux...');
  try {
    execSync('wsl -d OpenClaw -- echo ok', { stdio: 'pipe', timeout: 15000 });
    console.log('      ' + C.g + '[OK]' + C.nc);
  } catch {
    console.log('      ' + C.r + '[未安装]' + C.nc);
    console.log('');
    console.log('正在启动 WSL2 安装向导...');
    try { execSync('myclaw wsl2', { stdio: 'inherit' }); } catch {}
    console.log('');
    console.log('完成后再次运行 ' + C.y + 'myclaw start' + C.nc);
    return;
  }
  console.log('');

  // Step 2.5: 自动检测虚拟机屏蔽（safe）
  // const SAFE_ENABLED = true;
  const SAFE_ENABLED = false;
  if (SAFE_ENABLED) {
    console.log('[safe] 虚拟机屏蔽...');
    const restrict = require('./restrict');
    if (restrict.isAlreadySafe()) {
      console.log('      ' + C.g + '[已开启]' + C.nc);
    } else {
      console.log('      ' + C.y + '[未开启，正在启用...]' + C.nc);
      try { execSync('myclaw safe', { stdio: 'inherit', timeout: 30000 }); } catch {}
    }
    console.log('');
  }

  // Step 3: 检查 Gateway
  console.log('[3/4] Gateway...');
  let gatewayRunning = false;
  try {
    execSync('wsl -d OpenClaw -- pgrep -f "openclaw"', { stdio: 'pipe', timeout: 5000 });
    gatewayRunning = true;
    console.log('      ' + C.g + '[已在运行]' + C.nc);
  } catch {
    console.log('      ' + C.y + '[未启动]' + C.nc);
  }
  console.log('');

  // 无论 Gateway 是否已运行，都先检查更新 + patch
  console.log('[update] 检查 MyClaw 更新...');
  try { execSync('myclaw update', { stdio: 'inherit', timeout: 120000 }); } catch {}
  console.log('');

  console.log('[mc up] WSL 内更新 MyClaw + 刷新配置...');
  try {
    execSync('wsl -d OpenClaw -- mc up', { stdio: 'inherit', timeout: 120000 });
  } catch {}
  console.log('');

  if (!gatewayRunning) {
    // ============================================================
    // 首次启动: 在当前窗口直接 launch，不开新窗口，不刷图标
    // ============================================================
    console.log('[launch] 在当前窗口启动 Gateway...');

    // Step 4: 先打开浏览器（延迟几秒后 Gateway 就绑了）
    console.log('');
    console.log('[4/4] 打开浏览器 (Gateway 启动后自动连接)...');
    try { execSync('myclaw open', { stdio: 'inherit', timeout: 10000 }); } catch {}

    console.log('');
    console.log(BAR);
    console.log('  Gateway 正在当前窗口启动...');
    console.log('  关闭此窗口 = 停止服务');
    console.log(BAR);
    console.log('');

    // 直接在当前窗口执行 launch（阻塞，关窗口 = 停服务）
    try {
      execSync('wsl -d OpenClaw -- myclaw launch', {
        stdio: 'inherit',
      });
    } catch {}

  } else {
    // ============================================================
    // 非首次启动: Gateway 已在运行
    // ============================================================

    // 重启使 patch 生效
    console.log('[restart] 重启 Gateway 使插件生效...');
    try {
      execSync('wsl -d OpenClaw -- openclaw gateway restart', { stdio: 'pipe', timeout: 15000 });
      console.log('      ' + C.g + '[OK]' + C.nc);
    } catch {
      console.log('      ' + C.y + '[跳过]' + C.nc + ' 重启失败，手动 myclaw restart');
    }

    // Step 4: 打开浏览器
    console.log('');
    console.log('[4/4] 打开浏览器...');
    try { execSync('myclaw open', { stdio: 'inherit', timeout: 10000 }); } catch {}

    // 打开 WSL 终端
    console.log('');
    console.log('[terminal] 打开 WSL 终端...');
    try {
      execSync('start "OpenClaw Terminal" wsl -d OpenClaw --cd /root/.openclaw', {
        stdio: 'inherit',
        shell: true,
      });
    } catch {}

    // 刷新桌面图标（仅非首次才做）
    try { execSync('myclaw bat', { stdio: 'pipe', timeout: 10000 }); } catch {}

    console.log('');
    console.log(BAR);
    console.log('  OpenClaw 正在运行，浏览器已打开。');
    console.log(BAR);
  }
}

// ============================================================================
// Linux/Mac 启动流程（等同于 myclaw launch）
// ============================================================================

function startUnix() {
  const launch = require('./launch');
  return launch.run();
}

// ============================================================================
// 主入口
// ============================================================================

async function run() {
  console.log('');
  console.log('[' + C.b + 'MyClaw' + C.nc + '] ' + C.b + '智能启动' + C.nc);
  console.log(BAR);
  console.log('');

  if (isWindows) {
    startWindows();
  } else {
    await startUnix();
  }
}

module.exports = { run };
