#!/usr/bin/env node

/**
 * ============================================================================
 * MyClaw 虚拟机屏蔽（Windows 侧）
 * ============================================================================
 *
 * 只做一件事：禁用 WSL2 自动挂载 Windows 盘符
 * 如果已经开启，直接跳过。
 *
 * 使用方法：
 *   myclaw safe
 *
 * 前提：OpenClaw WSL2 发行版已安装（myclaw wsl2 完成）
 * ============================================================================
 */

const { execSync } = require('child_process');
const os = require('os');
const fs = require('fs');
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 DISTRO_NAME = 'OpenClaw';

function printInfo(msg) { console.log(C.b + '[信息]' + C.nc + ' ' + msg); }
function printSuccess(msg) { console.log(C.g + '[成功]' + C.nc + ' ' + msg); }
function printWarning(msg) { console.log(C.y + '[警告]' + C.nc + ' ' + msg); }
function printError(msg) { console.error(C.r + '[错误]' + C.nc + ' ' + msg); }

// 在 WSL 中执行命令
function wslExec(cmd) {
  try {
    return execSync('wsl -d ' + DISTRO_NAME + ' -- bash -c "' + cmd + '"', {
      encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'],
    }).trim();
  } catch {
    return null;
  }
}

// 通过临时脚本文件以 root 执行（只在 automount 未禁用时可用）
function wslRunScriptAsRoot(scriptContent) {
  const tmpDir = path.join(process.env.LOCALAPPDATA || os.tmpdir(), 'myclaw');
  try { fs.mkdirSync(tmpDir, { recursive: true }); } catch {}
  const scriptFile = path.join(tmpDir, 'safe-setup.sh');
  fs.writeFileSync(scriptFile, scriptContent, 'utf8');
  const wslPath = '/mnt/' + scriptFile.charAt(0).toLowerCase() + scriptFile.slice(2).replace(/\\/g, '/');
  try {
    execSync('wsl -d ' + DISTRO_NAME + ' -u root -- bash ' + wslPath, {
      encoding: 'utf8', stdio: 'pipe',
    });
    return true;
  } catch {
    return false;
  }
}

// 检测是否已开启
function isAlreadySafe() {
  const conf = wslExec('cat /etc/wsl.conf 2>/dev/null') || '';
  return conf.includes('enabled = false') || conf.includes('enabled=false');
}

// ============================================================================
// 主函数
// ============================================================================

function run() {
  if (!isWindows) {
    printError('此命令只能在 Windows 上运行');
    process.exit(1);
  }

  // 检查 WSL + OpenClaw
  try { execSync('wsl --version', { stdio: 'pipe' }); } catch {
    printError('未检测到 WSL。请先运行: myclaw wsl2');
    process.exit(1);
  }
  try {
    const list = execSync('wsl -l -q', { encoding: 'utf16le' });
    if (!list.includes(DISTRO_NAME)) {
      printError('未找到 ' + DISTRO_NAME + ' 发行版');
      process.exit(1);
    }
  } catch {
    printError('无法读取 WSL 发行版列表');
    process.exit(1);
  }

  // 已开启则跳过
  if (isAlreadySafe()) {
    printSuccess('虚拟机屏蔽已开启，无需重复执行');
    return true;
  }

  // 创建工作目录
  printInfo('创建工作目录...');
  wslExec('mkdir -p /root/.openclaw/workspace/myclaw');

  // 写入 /etc/wsl.conf
  printInfo('正在禁用自动挂载...');

  const existing = wslExec('cat /etc/wsl.conf 2>/dev/null') || '';
  let newContent;
  if (existing.includes('[automount]')) {
    // 替换 automount 段，同时确保有 interop 段
    newContent = existing.replace(/\[automount\][^\[]*/, '[automount]\nenabled = false\n');
    if (!newContent.includes('[interop]')) {
      newContent += '[interop]\nappendWindowsPath = false\n';
    } else if (!newContent.includes('appendWindowsPath')) {
      // 已有 [interop] 但没有 appendWindowsPath，追加
      newContent = newContent.replace(/\[interop\]/, '[interop]\nappendWindowsPath = false');
    }
  } else {
    // 没有 automount，追加两段
    newContent = existing + (existing.endsWith('\n') ? '' : '\n') + '[automount]\nenabled = false\n[interop]\nappendWindowsPath = false\n';
  }

  const script = [
    '#!/bin/bash',
    'cp /etc/wsl.conf /etc/wsl.conf.bak 2>/dev/null || true',
    'cat > /etc/wsl.conf << \'MYCLAW_EOF\'',
    newContent,
    'MYCLAW_EOF',
  ].join('\n');

  const ok = wslRunScriptAsRoot(script);
  if (!ok) {
    printError('写入 wsl.conf 失败');
    return false;
  }

  // 验证
  if (!isAlreadySafe()) {
    printError('配置验证失败');
    return false;
  }

  printSuccess('automount 已禁用');

  // 重启 WSL 使配置生效
  printInfo('正在重启 WSL2...');
  try {
    execSync('wsl --shutdown', { stdio: 'pipe', timeout: 15000 });
    printSuccess('WSL2 已重启');
  } catch {
    printWarning('请手动运行: wsl --shutdown');
  }

  return true;
}

// 导出检测函数供 start.js 使用
module.exports = { run, isAlreadySafe };
