/**
 * 直接测试 miniprogram-automator 的 launch 功能
 * 使用 npx 缓存中已 patch 的版本
 * 
 * 用法: node scripts/ops/test_automator_launch.js
 */
const path = require('path');
const fs = require('fs');

// 找到 npx 缓存中的 miniprogram-automator
const npxCacheBase = path.join(process.env.LOCALAPPDATA, 'npm-cache', '_npx');
let automatorPath = null;

for (const dir of fs.readdirSync(npxCacheBase)) {
  const candidate = path.join(npxCacheBase, dir, 'node_modules', 'miniprogram-automator');
  if (fs.existsSync(candidate)) {
    automatorPath = candidate;
    break;
  }
}

if (!automatorPath) {
  console.error('未找到 miniprogram-automator，请先运行 patch 脚本');
  process.exit(1);
}

console.log(`使用 automator: ${automatorPath}`);

// 验证 patch 状态
const launcherContent = fs.readFileSync(path.join(automatorPath, 'out', 'Launcher.js'), 'utf8');
if (launcherContent.includes('shell:!0') || launcherContent.includes('shell: true')) {
  console.log('✅ Launcher.js 已 patch (shell:true)');
} else {
  console.log('❌ Launcher.js 未 patch，先运行 patch_automator_spawn.js');
  process.exit(1);
}

const automator = require(automatorPath);

const PROJECT_PATH = 'C:\\NeoZQYY\\apps\\miniprogram';

async function main() {
  console.log(`\n尝试 launch 连接...`);
  console.log(`项目路径: ${PROJECT_PATH}`);
  
  try {
    const miniProgram = await automator.launch({
      projectPath: PROJECT_PATH,
    });
    console.log('✅ 连接成功!');
    
    // 获取系统信息
    const systemInfo = await miniProgram.systemInfo();
    console.log('系统信息:', JSON.stringify(systemInfo, null, 2));
    
    // 获取当前页面
    const page = await miniProgram.currentPage();
    console.log('当前页面:', page ? page.path : '无');
    
    await miniProgram.close();
    console.log('已断开连接');
  } catch (err) {
    console.error('❌ 连接失败:', err.message);
    console.error('错误详情:', err.stack);
  }
}

main();
