#!/usr/bin/env node

/**
 * ============================================================================
 * MyClaw Fix - 兜底修复命令
 * ============================================================================
 *
 * 使用: myclaw fix
 *
 * 运行后自动执行两件事：
 *   1. 强制下载并安装 WSL MSI（无论是否已装，确保补齐）
 *   2. 检查 Chrome 是否已安装，未装则下载并静默安装
 *
 * 设计原则：
 *   - 仅限 Windows 使用
 *   - 管理员权限运行（MSI 安装需要）
 *   - WSL 强制安装（兜底，避免漏装）
 *   - Chrome 按需安装（检测到才跳过）
 *   - 全自动：学生不需要做任何操作
 * ============================================================================
 */

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

// ============================================================================
// 配置
// ============================================================================

const CDN = {
  wsl: 'https://cdn.yiranlaoshi.com/software/myclaw/wsl.2.7.1.0.x64.msi',
  chrome: 'https://cdn.yiranlaoshi.com/software/myclaw/ChromeStandaloneSetup64.exe',
};

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' };

// ============================================================================
// 工具：启动 PowerShell 管理员窗口执行脚本
// ============================================================================

function launchElevatedPS(script) {
  const fs = require('fs');

  const tmpDir = process.env.LOCALAPPDATA
    ? path.join(process.env.LOCALAPPDATA, 'myclaw')
    : path.join(os.tmpdir(), 'myclaw');
  try { fs.mkdirSync(tmpDir, { recursive: true }); } catch {}
  const scriptPath = path.join(tmpDir, 'fix_installer.ps1');

  // UTF-8 with BOM — PowerShell 需要 BOM 才能正确读取中文
  const BOM = '\uFEFF';
  fs.writeFileSync(scriptPath, BOM + script, 'utf8');

  const escaped = scriptPath.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  const cmd = `powershell -Command "Start-Process powershell -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-NoExit','-File','${escaped}') -Verb RunAs"`;

  try {
    execSync(cmd, { stdio: 'inherit' });
    return true;
  } catch (err) {
    console.error('[' + C.r + '错误' + C.nc + '] 无法获取管理员权限: ' + err.message);
    console.log('建议右键终端选择【以管理员身份运行】后重试。');
    return false;
  }
}

// ============================================================================
// 检测 Chrome
// ============================================================================

function isChromeInstalled() {
  const locations = [
    path.join(process.env.PROGRAMFILES || 'C:\\Program Files', 'Google', 'Chrome', 'Application', 'chrome.exe'),
    path.join(process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe'),
    path.join(os.homedir(), 'AppData', 'Local', 'Google', 'Chrome', 'Application', 'chrome.exe'),
  ];

  const fs = require('fs');
  return locations.some(loc => {
    try { fs.accessSync(loc); return true; } catch { return false; }
  });
}

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

function run() {
  if (!isWindows) {
    console.error('[' + C.y + '提示' + C.nc + '] 本命令仅用于 Windows 系统。');
    process.exit(0);
  }

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

  console.log('');
  console.log('[' + C.b + 'MyClaw' + C.nc + '] ' + C.b + '兜底修复' + C.nc);
  console.log(BAR);
  console.log('');

  // Chrome 检测（WSL 不检测，强制安装）
  const chromeOK = isChromeInstalled();

  console.log('[检测结果]');
  console.log('  WSL:    ' + C.y + '[强制安装]' + C.nc);
  console.log('  Chrome: ' + (chromeOK ? C.g + '[已安装] 跳过' + C.nc : C.r + '[未安装] 将安装' + C.nc));
  console.log('');

  const needChrome = !chromeOK;
  const totalSteps = 2 + (needChrome ? 1 : 0);

  // Node 端也设置一下（当前终端环境）
  try { execSync('npm config set registry https://registry.npmmirror.com', { stdio: 'pipe' }); } catch {}

  let psScript = `
$ErrorActionPreference = 'Continue'
$Host.UI.RawUI.WindowTitle = 'MyClaw Fix'
try {
Write-Host ''
Write-Host '========================================'
Write-Host '  MyClaw 兜底修复'
Write-Host '========================================'
Write-Host ''

$dir = "$env:LOCALAPPDATA\\\\myclaw"
New-Item -ItemType Directory -Force -Path $dir | Out-Null

# ================================================
# [1/${totalSteps}] 配置 npm 中国镜像
# ================================================
Write-Host '[1/${totalSteps}] 配置 npm 中国镜像...'
try {
    npm config set registry https://registry.npmmirror.com 2>$null
    Write-Host '      [OK] registry -> https://registry.npmmirror.com'
} catch {
    Write-Host '      [跳过] npm 未安装或配置失败'
}
Write-Host ''

# ================================================
# [2/${totalSteps}] 强制安装 WSL
# ================================================
Write-Host '[2/${totalSteps}] 强制安装 WSL...'
Write-Host ''

Write-Host '  [a] 启用 Windows Subsystem for Linux...'
try {
    dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart 2>$null | Out-Null
    Write-Host '      [OK]'
} catch {
    Write-Host '      跳过 (可能已启用)'
}

Write-Host '  [b] 启用虚拟机平台...'
try {
    dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart 2>$null | Out-Null
    Write-Host '      [OK]'
} catch {
    Write-Host '      跳过 (可能已启用)'
}

$msi = "$dir\\\\wsl_fix.msi"
Write-Host '  [c] 下载 WSL 安装包...'
try {
    Start-BitsTransfer -Source '${CDN.wsl}' -Destination $msi -Description '下载 WSL' -DisplayName 'MyClaw Fix'
    Write-Host '      下载完成'
} catch {
    Write-Host '      BitsTransfer 失败，尝试 Invoke-WebRequest...'
    try {
        Invoke-WebRequest -Uri '${CDN.wsl}' -OutFile $msi -UseBasicParsing
        Write-Host '      下载完成'
    } catch {
        Write-Host '      [失败] 下载失败，请检查网络'
    }
}

if (Test-Path $msi) {
    Write-Host '  [d] 静默安装 WSL...'
    Start-Process msiexec.exe -ArgumentList @('/i', $msi, '/quiet', '/norestart') -Wait -NoNewWindow
    Write-Host '      [OK]'
}
Write-Host ''
`;

  // === Chrome（按需）===
  if (needChrome) {
    psScript += `
# ================================================
# [3/${totalSteps}] 安装 Chrome
# ================================================
Write-Host '[3/${totalSteps}] 安装 Chrome...'
Write-Host ''

$chromeExists = $false
$chromePaths = @(
    "$env:ProgramFiles\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe",
    "\${env:ProgramFiles(x86)}\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe",
    "$env:LOCALAPPDATA\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe"
)
foreach ($cp in $chromePaths) {
    if (Test-Path $cp) { $chromeExists = $true; break }
}

if ($chromeExists) {
    Write-Host '  Chrome 已安装，跳过'
} else {
    $exe = "$dir\\\\ChromeSetup.exe"
    Write-Host '  [a] 下载 Chrome 安装包...'
    try {
        Start-BitsTransfer -Source '${CDN.chrome}' -Destination $exe -Description '下载 Chrome' -DisplayName 'MyClaw Fix'
        Write-Host '      下载完成'
    } catch {
        Write-Host '      BitsTransfer 失败，尝试 Invoke-WebRequest...'
        try {
            Invoke-WebRequest -Uri '${CDN.chrome}' -OutFile $exe -UseBasicParsing
            Write-Host '      下载完成'
        } catch {
            Write-Host '      [失败] 下载失败，请检查网络'
        }
    }

    if (Test-Path $exe) {
        Write-Host '  [b] 安装 Chrome (静默)...'
        Start-Process $exe -ArgumentList '/silent /install' -Wait -NoNewWindow
        Write-Host '      [OK]'
    }
}
Write-Host ''
`;
  }

  // === 结尾 ===
  psScript += `
Write-Host '========================================'
Write-Host '  修复完成!'
Write-Host '========================================'
Write-Host ''
Write-Host '  [重要] WSL 安装后可能需要 重启电脑 才能生效'
Write-Host '  重启后运行: myclaw wsl2'
Write-Host ''

} catch {
    Write-Host ''
    Write-Host '========================================'
    Write-Host "  [异常] 发生错误: $_"
    Write-Host '  请截图此窗口内容后联系老师'
    Write-Host '========================================'
} finally {
    Write-Host ''
    Write-Host '按任意键关闭此窗口...'
    $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
}
`;

  // 显示即将执行的操作
  console.log('[即将执行]');
  console.log('  • 强制下载并安装 WSL (' + CDN.wsl + ')');
  if (needChrome) console.log('  • 下载并安装 Chrome (' + CDN.chrome + ')');
  console.log('');
  console.log('[' + C.y + '注意' + C.nc + '] 请在 UAC 弹窗中点击【是】');
  console.log('');

  if (launchElevatedPS(psScript)) {
    console.log('[' + C.g + '已启动' + C.nc + '] 请查看新弹出的蓝色窗口');
    console.log('');
    console.log('WSL 安装完成后可能需要 ' + C.y + '重启电脑' + C.nc);
    console.log('重启后运行 ' + C.y + 'myclaw wsl2' + C.nc + ' 继续安装');
    console.log('');
  }
}

module.exports = { run };
