/**
 * 启动微信开发者工具 CLI auto 命令
 * 自动回答 "y" 确认开启服务端口
 * 然后等待自动化端口启动
 */
const { spawn } = require('child_process');
const net = require('net');

const CLI = 'C:\\DEV\\WechatDevtools\\cli.bat';
const PROJECT = 'C:\\NeoZQYY\\apps\\miniprogram';
const AUTO_PORT = 9420;

console.log('启动 CLI auto 命令...');
console.log(`CLI: ${CLI}`);
console.log(`项目: ${PROJECT}`);
console.log(`自动化端口: ${AUTO_PORT}`);

const child = spawn(CLI, [
  'auto',
  '--project', PROJECT,
  '--auto-port', String(AUTO_PORT),
], {
  shell: true,
  stdio: ['pipe', 'pipe', 'pipe'],
});

let output = '';
let answered = false;

child.stdout.on('data', (data) => {
  const text = data.toString();
  output += text;
  process.stdout.write(`[stdout] ${text}`);
  
  // 检测到交互式提示，自动回答 y
  if (!answered && text.includes('Enable IDE Service')) {
    console.log('\n>>> 检测到服务端口确认提示，自动回答 y');
    child.stdin.write('y\n');
    answered = true;
  }
});

child.stderr.on('data', (data) => {
  const text = data.toString();
  output += text;
  process.stderr.write(`[stderr] ${text}`);
});

child.on('close', (code) => {
  console.log(`\nCLI 退出，代码: ${code}`);
  
  // 检查端口
  setTimeout(async () => {
    const socket = new net.Socket();
    socket.setTimeout(3000);
    socket.on('connect', () => {
      socket.destroy();
      console.log(`✅ 端口 ${AUTO_PORT} 已开放！自动化启动成功`);
      process.exit(0);
    });
    socket.on('error', () => {
      socket.destroy();
      console.log(`❌ 端口 ${AUTO_PORT} 未开放`);
      console.log('完整输出:', output);
      process.exit(1);
    });
    socket.connect(AUTO_PORT, '127.0.0.1');
  }, 2000);
});

// 30 秒超时
setTimeout(() => {
  console.error('30 秒超时');
  child.kill();
  process.exit(1);
}, 30000);
