/**
 * 测试 miniprogram-automator launch（带超时和详细日志）
 */
const path = require('path');
const fs = require('fs');

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('未找到 automator'); process.exit(1); }
console.log(`automator: ${automatorPath}`);

const automator = require(automatorPath);
const PROJECT_PATH = 'C:\\NeoZQYY\\apps\\miniprogram';

// 30 秒超时
const timer = setTimeout(() => {
  console.error('❌ 30 秒超时，launch 未完成');
  process.exit(1);
}, 30000);

async function main() {
  try {
    console.log(`[${new Date().toISOString()}] 开始 launch...`);
    const mp = await automator.launch({ projectPath: PROJECT_PATH });
    clearTimeout(timer);
    console.log(`[${new Date().toISOString()}] ✅ 连接成功!`);
    const page = await mp.currentPage();
    console.log('当前页面:', page ? page.path : '无');
    await mp.close();
  } catch (err) {
    clearTimeout(timer);
    console.error(`[${new Date().toISOString()}] ❌ 失败: ${err.message}`);
    if (err.stack) console.error(err.stack.split('\n').slice(0, 5).join('\n'));
  }
}
main();
