/**
 * 测试微信开发者工具 v2 CLI API
 * 端口 16866 使用 v2 路由
 */
const http = require('http');
const net = require('net');

const PORT = 16866;

function httpRequest(method, path, body) {
  return new Promise((resolve) => {
    const options = {
      hostname: '127.0.0.1', port: PORT, path, method,
      headers: { 'Content-Type': 'application/json' },
      timeout: 10000,
    };
    const req = http.request(options, (res) => {
      // 跟随重定向
      if (res.statusCode === 302 && res.headers.location) {
        console.log(`  → 重定向到 ${res.headers.location}`);
        httpRequest(method, res.headers.location, body).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 }));
    if (body) req.write(JSON.stringify(body));
    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 main() {
  // 1. 测试 v2 端点
  console.log('=== v2 API 测试 ===');
  
  const v2Endpoints = [
    ['GET', '/v2/open?projectpath=C%3A%5CNeoZQYY%5Capps%5Cminiprogram'],
    ['GET', '/v2/auto?projectpath=C%3A%5CNeoZQYY%5Capps%5Cminiprogram'],
    ['GET', '/v2/auto/start?projectpath=C%3A%5CNeoZQYY%5Capps%5Cminiprogram'],
    ['GET', '/v2/status'],
    ['GET', '/v2/port'],
    ['GET', '/v2/isopen'],
  ];

  for (const [method, ep] of v2Endpoints) {
    console.log(`\n${method} ${ep}`);
    const r = await httpRequest(method, ep);
    console.log(`  状态: ${r.status}`);
    console.log(`  响应: ${r.data.substring(0, 500)}`);
  }

  // 2. 等待后扫描端口
  console.log('\n\n=== 等待 5 秒后扫描端口 ===');
  await new Promise(r => setTimeout(r, 5000));
  
  for (const p of [9220, 9222, 9420, 9421, 16866, 16867]) {
    const open = await testPort(p);
    if (open) console.log(`端口 ${p}: ✅ 开放`);
  }
  
  // 3. 宽范围扫描（查找动态分配的端口）
  console.log('\n=== 宽范围端口扫描 (9200-9500) ===');
  const promises = [];
  for (let p = 9200; p <= 9500; p++) {
    promises.push(testPort(p).then(open => open ? p : null));
  }
  const results = (await Promise.all(promises)).filter(Boolean);
  if (results.length > 0) {
    console.log('开放端口:', results.join(', '));
    for (const p of results) {
      const r = await httpRequest('GET', `/json/version`);
      console.log(`  ${p} /json/version: ${r.data.substring(0, 200)}`);
    }
  } else {
    console.log('范围内无开放端口');
  }
}

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