/**
 * ============================================================================
 * MyClaw Patch Python Deps
 * ============================================================================
 *
 * 功能：
 *   读取 myclaw 根目录下的 requirements.txt，检查并安装所有 Python 依赖。
 *   幂等：已安装的包跳过，只安装缺失的。
 * ============================================================================
 */

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

function patchPythonDeps() {
  const reqPath = path.join(__dirname, '..', 'requirements.txt');

  if (!fs.existsSync(reqPath)) {
    console.log('[myclaw-python-deps] ⚠ 未找到 requirements.txt，跳过');
    return { success: true, installed: [] };
  }

  const packages = fs.readFileSync(reqPath, 'utf8')
    .split('\n')
    .map(l => l.trim())
    .filter(l => l && !l.startsWith('#'));

  if (packages.length === 0) {
    console.log('[myclaw-python-deps] ✅ requirements.txt 为空，无需安装');
    return { success: true, installed: [] };
  }

  console.log('[myclaw-python-deps] 检查 Python 依赖...');

  const missing = [];

  for (const pkg of packages) {
    // pip 包名转 import 名：把连字符换成下划线（volcengine → volcengine，boto3 → boto3）
    const importName = pkg.split(/[>=<!]/)[0].trim().replace(/-/g, '_');
    try {
      execSync(`python3 -c "import ${importName}"`, { stdio: 'pipe' });
      console.log('[myclaw-python-deps] ✅ 已安装: ' + pkg);
    } catch {
      console.log('[myclaw-python-deps] ⚠ 缺少: ' + pkg);
      missing.push(pkg);
    }
  }

  if (missing.length === 0) {
    console.log('[myclaw-python-deps] ✅ 所有依赖已就绪');
    return { success: true, installed: [] };
  }

  console.log('[myclaw-python-deps] → 安装缺失依赖: ' + missing.join(', '));

  const installed = [];
  const failed = [];

  for (const pkg of missing) {
    try {
      execSync(`pip3 install -q --break-system-packages ${pkg}`, { stdio: 'pipe' });
      console.log('[myclaw-python-deps] ✅ 已安装: ' + pkg);
      installed.push(pkg);
    } catch (err) {
      const detail = (err.stderr && err.stderr.toString().trim()) || err.message;
      console.log('[myclaw-python-deps] ❌ 安装失败: ' + pkg);
      console.log('    ' + detail);
      failed.push(pkg);
    }
  }

  if (failed.length > 0) {
    console.log('[myclaw-python-deps] ⚠ 以下依赖安装失败，请手动运行:');
    console.log('    pip3 install ' + failed.join(' '));
  }

  return { success: failed.length === 0, installed, failed };
}

module.exports = { patchPythonDeps };
