/**
 * 通过 v2 CLI API 启动自动化，获取 WebSocket 端口
 */
const http = require('http');
const net = require('net');

const PORT = 16866;
const PROJECT = 'C:\\NeoZQYY\\apps\\miniprogram';

function httpReq(method, path, followRedirect = true) {
  return new Promise((resolve) => {
    const options = {
      hostname: '127.0.0.1', port: PORT, path, method,
      timeout: 15000,
    };
    const req = http.request(options, (res) => {
      if (followRedirect && res.statusCode === 302 && res.headers.location) {
        httpReq(method, res.headers.location, true).then(resolve);
        return;
      }
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve({ status: res.statusCode, data, headers: res.headers }));
    });
    req.on('error', (err) => resolve({ status: 0, data: err.message }));
    req.on('timeout', () => { req.destroy(); resolve({ status: 0, data: 'timeout' }); });
    req.end();
  });
}

function testPort(port) {
  return new Promise((resolve) => {
    const socket = new net.Socket();
    socket.setTimeout(2000);
    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');
  });
}

async function scanPorts(label) {
  console.log(`\n--- ${label}: 扫描端口 ---`);
  // 扫描常见范围 + 宽范围
  const ranges = [[9200, 9500], [16860, 16880], [19000, 19100]];
  for (const [start, end] of ranges) {
    const promises = [];
    for (let p = start; p <= end; p++) {
      promises.push(testPort(p).then(open => open ? p : null));
    }
    const open = (await Promise.all(promises)).filter(Boolean);
    if (open.length > 0) console.log(`  ${start}-${end}: ${open.join(', ')}`);
  }
}

async function main() {
  const encoded = encodeURIComponent(PROJECT);

  // 尝试各种参数名和路径组合
  const attempts = [
    `/v2/auto?project=${encoded}`,
    `/v2/auto?project=${encoded}&auto-port=9420`,
    `/v2/auto?appid=wx1234567890abcdef&project=${encoded}`,
    `/auto?project=${encoded}`,
    `/v2/open?project=${encoded}&auto-port=9420`,
    `/v2/open?projectpath=${encoded}&auto-port=9420`,
  ];

  for (const url of attempts) {
    console.log(`\nGET ${url}`);
    const r = await httpReq('GET', url);
    console.log(`  [${r.status}] ${r.data.substring(0, 300)}`);
    
    // 如果成功，检查响应中是否有端口信息
    if (r.status === 200) {
      try {
        const json = JSON.parse(r.data);
        if (json.automationPort || json.wsEndpoint || json.port) {
          console.log('  🎯 找到自动化端口信息:', JSON.stringify(json));
        }
      } catch {}
    }
  }

  // 等待后扫描
  await new Promise(r => setTimeout(r, 3000));
  await scanPorts('尝试后');
}

const timer = setTimeout(() => { console.error('超时'); process.exit(1); }, 45000);
main().then(() => { clearTimeout(timer); process.exit(0); });
