const WebSocket = require('ws');
const { HttpsProxyAgent } = require('https-proxy-agent');

/**
 * 原生WebSocket代理测试
 * 测试IPRoyal代理是否支持WebSocket连接
 */

async function testProxyWebSocket() {
  console.log('🚀 开始原生WebSocket代理测试...\n');

  // 生成动态代理密码
  const sessionId = Math.random().toString(36).substr(2, 8);
  const proxyPassword = `test123456_country-jp,sg_session-${sessionId}_lifetime-59m`;
  const proxyUrl = `http://tuxla:${proxyPassword}@geo.iproyal.com:12321`;

  console.log('🔐 代理配置:');
  console.log(`  代理URL: http://tuxla:***@geo.iproyal.com:12321`);
  console.log(`  会话ID: ${sessionId}`);

  // 测试1: 不使用代理的WebSocket连接
  console.log('\n📡 测试1: 直接WebSocket连接（无代理）...');
  try {
    await testWebSocketConnection('wss://ws.pacifica.fi/ws', null);
  } catch (error) {
    console.log(`❌ 直接连接失败: ${error.message}`);
  }

  // 测试2: 使用HTTP代理的WebSocket连接
  console.log('\n🌐 测试2: 通过IPRoyal HTTP代理的WebSocket连接...');
  try {
    const proxyAgent = new HttpsProxyAgent(proxyUrl);
    await testWebSocketConnection('wss://ws.pacifica.fi/ws', proxyAgent);
  } catch (error) {
    console.log(`❌ 代理连接失败: ${error.message}`);
  }

  console.log('\n✅ WebSocket代理测试完成!');
}

function testWebSocketConnection(url, agent) {
  return new Promise((resolve, reject) => {
    console.log(`  🔗 连接到: ${url}`);
    console.log(`  🌐 代理: ${agent ? '启用' : '禁用'}`);

    const wsOptions = {};
    if (agent) {
      wsOptions.agent = agent;
    }

    const ws = new WebSocket(url, wsOptions);
    const startTime = Date.now();

    // 设置超时
    const timeout = setTimeout(() => {
      ws.terminate();
      reject(new Error('连接超时 (15秒)'));
    }, 15000);

    ws.on('open', () => {
      const duration = Date.now() - startTime;
      console.log(`  ✅ WebSocket连接成功! 耗时: ${duration}ms`);

      // 发送一个测试消息
      const testMessage = JSON.stringify({
        id: `test-${Date.now()}`,
        method: 'ping'
      });

      console.log(`  📤 发送测试消息: ${testMessage}`);
      ws.send(testMessage);

      // 等待响应
      setTimeout(() => {
        clearTimeout(timeout);
        ws.close();
        resolve();
      }, 3000);
    });

    ws.on('message', (data) => {
      console.log(`  📥 收到消息: ${data.toString()}`);
    });

    ws.on('close', (code, reason) => {
      console.log(`  🔒 连接关闭: ${code} ${reason}`);
    });

    ws.on('error', (error) => {
      console.log(`  ❌ WebSocket错误: ${error.message}`);
      clearTimeout(timeout);
      reject(error);
    });
  });
}

// 运行测试
if (require.main === module) {
  testProxyWebSocket().catch(error => {
    console.error('🚨 测试失败:', error);
    process.exit(1);
  });
}

module.exports = { testProxyWebSocket };