// 测试 miniprogram-automator 直接连接微信开发者工具
// 用法: npx -y miniprogram-automator && node scripts/ops/test_wx_connect.js
// 或先 npm install miniprogram-automator 再运行

const net = require('net');
const http = require('http');

// 不依赖 miniprogram-automator，直接用原生 WebSocket 测试端口连通性
async function testPort(port) {
  return new Promise((resolve) => {
    const socket = new net.Socket();
    socket.setTimeout(3000);
    socket.on('connect', () => { socket.destroy(); resolve(true); });
    socket.on('timeout', () => { socket.destroy(); resolve(false); });
    socket.on('error', () => { socket.destroy(); resolve(false); });
    socket.connect(port, '127.0.0.1');
  });
}

// 测试 HTTP 端点（开发者工具的 /json 接口）
async function testHttp(port) {
  return new Promise((resolve) => {
    http.get(`http://127.0.0.1:${port}/json`, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve(data));
    }).on('error', (err) => resolve(`HTTP 错误: ${err.message}`));
  });
}

async function main() {
  const port = 16866;
  console.log(`Node.js 版本: ${process.version}`);
  console.log(`测试端口 ${port} 连通性...`);
  
  const portOpen = await testPort(port);
  console.log(`端口 ${port}: ${portOpen ? '✅ 开放' : '❌ 未开放'}`);
  
  if (portOpen) {
    console.log(`\n测试 HTTP /json 端点...`);
    const httpResult = await testHttp(port);
    console.log(`HTTP 响应: ${httpResult.substring(0, 500)}`);
  }
}

main();
