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

// 神龙代理配置
const SHENLONG_CONFIG = {
  productKey: 'o2ihwv3e',
  signature: 'ccff437b0c211d7a758b0926cbdcf958',
  regionCode: '310000',  // 上海
  platform: 'weixin'
};

// 测试代理
function testProxy() {
  return new Promise((resolve, reject) => {
    console.log('\n🔍 测试神龙代理对微信视频号的可用性...');
    console.log('配置:', JSON.stringify(SHENLONG_CONFIG, null, 2));
    
    const postData = JSON.stringify(SHENLONG_CONFIG);
    
    const req = http.request('http://127.0.0.1:5005/proxy/test', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      },
      timeout: 30000
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          console.log('\n✅ 代理测试结果:');
          console.log(JSON.stringify(result, null, 2));
          resolve(result);
        } catch (e) {
          console.error('❌ 解析响应失败:', e);
          reject(e);
        }
      });
    });
    
    req.on('error', (e) => {
      console.error('❌ 请求失败:', e.message);
      console.log('\n💡 Python 服务未启动，让我直接测试神龙 API...');
      testShenlongAPI().then(resolve).catch(reject);
    });
    
    req.on('timeout', () => {
      console.error('❌ 请求超时');
      req.destroy();
      testShenlongAPI().then(resolve).catch(reject);
    });
    
    req.write(postData);
    req.end();
  });
}

// 直接测试神龙 API
async function testShenlongAPI() {
  return new Promise((resolve, reject) => {
    console.log('\n🔍 直接测试神龙代理 API...');
    
    const params = new URLSearchParams({
      key: SHENLONG_CONFIG.productKey,
      sign: SHENLONG_CONFIG.signature,
      count: 1,
      pattern: 'json',
      mr: 1,
      area: SHENLONG_CONFIG.regionCode
    });
    
    const url = `http://api.shenlongip.com/ip?${params.toString()}`;
    console.log('API URL:', url);
    
    http.get(url, {
      headers: {
        'User-Agent': 'Mozilla/5.0',
        'Accept': 'application/json'
      },
      timeout: 15000
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        console.log('\n神龙 API 响应:');
        try {
          const result = JSON.parse(data);
          console.log(JSON.stringify(result, null, 2));
          
          if (result.code === 200 && result.data && result.data.length > 0) {
            const proxy = result.data[0];
            console.log(`\n✅ 获取到代理IP: ${proxy.ip}:${proxy.port}`);
            console.log(`   城市: ${proxy.city}`);
            console.log(`   运营商: ${proxy.isp}`);
            
            // 测试代理连通性
            testProxyConnectivity(proxy.ip, proxy.port).then(() => {
              resolve(result);
            }).catch(reject);
          } else {
            console.log('\n❌ 获取代理失败:', result.msg || '未知错误');
            resolve(result);
          }
        } catch (e) {
          console.log('原始响应:', data);
          resolve({ raw: data });
        }
      });
    }).on('error', (e) => {
      console.error('❌ 神龙 API 请求失败:', e.message);
      reject(e);
    });
  });
}

// 测试代理连通性
function testProxyConnectivity(host, port) {
  return new Promise((resolve, reject) => {
    console.log(`\n🔍 测试代理连通性: ${host}:${port}...`);
    
    const options = {
      hostname: host,
      port: port,
      path: 'http://myip.ipip.net',
      method: 'GET',
      timeout: 10000
    };
    
    const req = http.request(options, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        console.log('\n✅ 代理连通性测试成功');
        console.log('IP信息:', data.trim());
        resolve();
      });
    });
    
    req.on('error', (e) => {
      console.error('❌ 代理连通性测试失败:', e.message);
      resolve(); // 不reject，继续
    });
    
    req.on('timeout', () => {
      console.error('❌ 代理连接超时');
      req.destroy();
      resolve();
    });
    
    req.end();
  });
}

// 主函数
async function main() {
  try {
    console.log('🚀 开始测试 Task #61 的代理配置');
    console.log('=' .repeat(60));
    
    await testProxy();
    
    console.log('\n' + '=' .repeat(60));
    console.log('✅ 测试完成');
    
  } catch (error) {
    console.error('\n❌ 测试失败:', error);
  }
}

main();
