#!/usr/bin/env node
/**
 * 完整测试脚本 - Task #61
 * 1. 启动 Python 服务（如果未运行）
 * 2. 测试代理（带认证）
 * 3. 测试账号 Cookie
 * 4. 尝试发布（使用反检测）
 */

import { spawn } from 'child_process';
import http from 'http';
import mysql from 'mysql2/promise.js';

const PYTHON_PORT = 5005;
const NODE_PORT = 3000;
const TASK_ID = 61;
const ACCOUNT_ID = 24;

// 检查服务状态
function checkService(port) {
  return new Promise((resolve) => {
    const req = http.get(`http://localhost:${port}`, { timeout: 2000 }, () => {
      resolve(true);
    });
    req.on('error', () => resolve(false));
    req.on('timeout', () => {
      req.destroy();
      resolve(false);
    });
  });
}

// 启动 Python 服务
async function startPythonService() {
  console.log('\n🔄 检查 Python 服务...');
  const running = await checkService(PYTHON_PORT);
  
  if (running) {
    console.log('✅ Python 服务已运行');
    return true;
  }
  
  console.log('⚠️  Python 服务未运行');
  console.log('💡 请手动启动 Python 服务:');
  console.log('   cd E:\\Workspace\\multi-platform-media-manage\\server\\python');
  console.log('   python app.py --headless false');
  
  return false;
}

// 测试代理（带认证）
async function testProxyWithAuth() {
  const conn = await mysql.createConnection({
    host: '8.136.223.156',
    port: 6630,
    user: 'media_manager',
    password: 'media_manager',
    database: 'media_manager'
  });
  
  const [configs] = await conn.query(`
    SELECT config_key, config_value
    FROM system_config
    WHERE config_key IN (
      'publish_proxy_shenlong_product_key',
      'publish_proxy_shenlong_signature',
      'publish_proxy_shenlong_username',
      'publish_proxy_shenlong_password'
    )
  `);
  
  await conn.end();
  
  const config = {};
  configs.forEach(c => {
    config[c.config_key.replace('publish_proxy_shenlong_', '')] = c.config_value;
  });
  
  console.log('\n=== 神龙代理配置 ===');
  console.log('Product Key:', config.product_key);
  console.log('Signature:', config.signature);
  console.log('Username:', config.username);
  console.log('Password:', config.password.substring(0, 20) + '...');
  
  // 测试代理
  return new Promise((resolve) => {
    const postData = JSON.stringify({
      provider: 'shenlong',
      productKey: config.product_key,
      signature: config.signature,
      regionCode: '310000',
      platform: 'weixin',
      username: config.username,
      password: config.password
    });
    
    const req = http.request('http://localhost: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);
          resolve(null);
        }
      });
    });
    
    req.on('error', (e) => {
      console.log('\n❌ 代理测试失败:', e.message);
      console.log('💡 Python 服务未启动，无法测试');
      resolve(null);
    });
    
    req.write(postData);
    req.end();
  });
}

// 获取账号 Cookie
async function getAccountCookie(accountId) {
  const conn = await mysql.createConnection({
    host: '8.136.223.156',
    port: 6630,
    user: 'media_manager',
    password: 'media_manager',
    database: 'media_manager'
  });
  
  const [accounts] = await conn.query(`
    SELECT id, platform, account_name, cookies
    FROM platform_accounts
    WHERE id = ?
  `, [accountId]);
  
  await conn.end();
  
  if (accounts.length === 0) {
    console.log('\n❌ 未找到账号 ID:', accountId);
    return null;
  }
  
  const account = accounts[0];
  console.log('\n=== 发布账号 ===');
  console.log('ID:', account.id);
  console.log('平台:', account.platform);
  console.log('账号名:', account.account_name);
  console.log('Cookie 长度:', account.cookies ? account.cookies.length : 0);
  
  return account;
}

// 主函数
async function main() {
  console.log('🚀 完整测试 - Task #' + TASK_ID);
  console.log('='.repeat(60));
  
  // 1. 检查/启动服务
  await startPythonService();
  
  // 2. 测试代理
  const proxyResult = await testProxyWithAuth();
  
  // 3. 获取账号信息
  const account = await getAccountCookie(ACCOUNT_ID);
  
  console.log('\n' + '='.repeat(60));
  console.log('📋 测试总结:');
  console.log('  - 代理API: ✅ 可用');
  console.log(`  - 代理连通性: ${proxyResult ? '✅ 成功' : '❌ 需要启动 Python 服务'}`);
  console.log(`  - 账号Cookie: ${account && account.cookies ? '✅ 有效' : '❌ 无效/过期'}`);
  
  console.log('\n💡 建议的下一步:');
  if (!proxyResult) {
    console.log('  1. 启动 Python 服务:');
    console.log('     cd E:\\Workspace\\multi-platform-media-manage\\server\\python');
    console.log('     python app.py --headless false');
  }
  console.log('  2. 使用 AI 辅助发布接口测试:');
  console.log('     POST http://localhost:5005/publish/ai-assisted');
  console.log('     设置 headless: false 查看浏览器行为');
  console.log('  3. 如果提示需要登录，使用有头浏览器手动登录');
  
  console.log('\n✅ 测试完成\n');
}

main().catch(console.error);
