/**
 * 测试多种连接方式：
 * 1. 通过 CLI HTTP 端口查询自动化信息
 * 2. 扫描常见自动化端口
 * 3. 尝试 automator.connect()
 */
const http = require('http');
const net = require('net');
const path = require('path');
const fs = require('fs');

function httpGet(url) {
  return new Promise((resolve) => {
    http.get(url, { timeout: 5000 }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => resolve({ status: res.statusCode, data }));
    }).on('error', (err) => resolve({ status: 0, data: err.message }));
  });
}

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() {
  const CLI_PORT = 16866;
  
  // 1. 查询 CLI HTTP 端口的各种端点
  console.log('=== 1. 查询 CLI HTTP 端点 ===');
  const endpoints = [
    '/json', '/json/version', '/json/list',
    '/', '/status', '/api/status',
    '/open', '/auto', '/automation'
  ];
  for (const ep of endpoints) {
    const r = await httpGet(`http://127.0.0.1:${CLI_PORT}${ep}`);
    const preview = r.data.substring(0, 200).replace(/\n/g, ' ');
    console.log(`  ${ep} → [${r.status}] ${preview}`);
  }

  // 2. 扫描端口范围
  console.log('\n=== 2. 扫描自动化端口 ===');
  const portsToScan = [
    9220, 9221, 9222, 9223, 9224, 9225,
    9420, 9421, 9422,
    16866, 16867, 16868,
    // 动态端口范围
    ...Array.from({length: 20}, (_, i) => 19000 + i),
  ];
  const openPorts = [];
  for (const p of portsToScan) {
    const open = await testPort(p);
    if (open) {
      openPorts.push(p);
      console.log(`  端口 ${p}: ✅ 开放`);
      // 尝试 HTTP
      const r = await httpGet(`http://127.0.0.1:${p}/json/version`);
      if (r.status === 200) console.log(`    /json/version: ${r.data.substring(0, 200)}`);
    }
  }
  if (openPorts.length === 0) console.log('  未发现开放端口');

  // 3. 尝试通过 CLI 开启自动化
  console.log('\n=== 3. 尝试 CLI 开启自动化 ===');
  // 微信开发者工具 CLI 的 /open 端点可以打开项目并启用自动化
  const openResult = await httpGet(
    `http://127.0.0.1:${CLI_PORT}/open?projectpath=C%3A%5CNeoZQYY%5Capps%5Cminiprogram`
  );
  console.log(`  /open 响应: [${openResult.status}] ${openResult.data.substring(0, 300)}`);

  // 等待 3 秒让自动化端口启动
  await new Promise(r => setTimeout(r, 3000));

  // 4. 再次扫描
  console.log('\n=== 4. 再次扫描端口 ===');
  for (const p of [9420, 9421, 9222, ...openPorts]) {
    const open = await testPort(p);
    if (open) {
      console.log(`  端口 ${p}: ✅ 开放`);
      const r = await httpGet(`http://127.0.0.1:${p}/json/version`);
      if (r.status === 200) console.log(`    /json/version: ${r.data.substring(0, 200)}`);
    }
  }
}

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