#!/usr/bin/env node
/**
 * 测试发布任务 #61
 * - 测试代理对微信视频号的可用性
 * - 测试账号 Cookie 有效性
 */

const http = require('http');

// 配置
const PYTHON_API = 'http://localhost:5005';
const TASK_ID = 61;
const ACCOUNT_ID = 24;

// 从数据库获取的代理配置
const PROXY_CONFIG = {
  city: "上海",
  enabled: true,
  provider: "shenlong",
  regionCode: "310000",
  regionName: "市辖区",
  regionPath: ["31", "310000"]
};

// 测试代理
async function testProxy() {
  return new Promise((resolve, reject) => {
    console.log('\n=== 1️⃣ 测试代理配置 ===');
    console.log('代理配置:', JSON.stringify(PROXY_CONFIG, null, 2));
    
    const postData = JSON.stringify({
      ...PROXY_CONFIG,
      platform: 'weixin'  // 测试对微信平台的可用性
    });
    
    const req = http.request(`${PYTHON_API}/proxy/test`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      }
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          console.log('\n代理测试结果:', JSON.stringify(result, null, 2));
          resolve(result);
        } catch (e) {
          reject(e);
        }
      });
    });
    
    req.on('error', (e) => {
      console.error('❌ 代理测试失败:', e.message);
      reject(e);
    });
    
    req.write(postData);
    req.end();
  });
}

// 测试发布（带代理）
async function testPublish() {
  return new Promise((resolve, reject) => {
    console.log('\n=== 2️⃣ 测试发布 ===');
    console.log('任务ID:', TASK_ID);
    console.log('账号ID:', ACCOUNT_ID);
    
    // 从 Node.js API 获取完整任务信息
    http.get(`http://localhost:3000/api/publish/tasks/${TASK_ID}`, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', async () => {
        try {
          const taskData = JSON.parse(data);
          if (!taskData.success) {
            throw new Error(taskData.error || '获取任务失败');
          }
          
          console.log('\n任务信息:', JSON.stringify({
            id: taskData.data.id,
            title: taskData.data.title,
            status: taskData.data.status,
            video_path: taskData.data.video_path,
            proxy: taskData.data.publish_proxy
          }, null, 2));
          
          // 调用 Python AI 发布接口
          console.log('\n开始测试发布...');
          const publishData = JSON.stringify({
            platform: 'weixin',
            cookie: '', // 需要从数据库获取
            title: taskData.data.title,
            description: taskData.data.description,
            video_path: `E:\\Workspace\\multi-platform-media-manage${taskData.data.video_path}`,
            headless: false,  // 显示浏览器
            return_screenshot: true,
            proxy: taskData.data.publish_proxy,
            user_id: taskData.data.user_id,
            publish_task_id: taskData.data.id,
            publish_account_id: ACCOUNT_ID
          });
          
          const publishReq = http.request(`${PYTHON_API}/publish/ai-assisted`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Content-Length': Buffer.byteLength(publishData)
            }
          }, (publishRes) => {
            let publishResult = '';
            publishRes.on('data', chunk => publishResult += chunk);
            publishRes.on('end', () => {
              try {
                const result = JSON.parse(publishResult);
                console.log('\n发布结果:', JSON.stringify({
                  success: result.success,
                  status: result.status,
                  error: result.error,
                  need_captcha: result.need_captcha,
                  captcha_type: result.captcha_type
                }, null, 2));
                resolve(result);
              } catch (e) {
                reject(e);
              }
            });
          });
          
          publishReq.on('error', (e) => {
            console.error('❌ 发布请求失败:', e.message);
            reject(e);
          });
          
          publishReq.write(publishData);
          publishReq.end();
          
        } catch (e) {
          reject(e);
        }
      });
    }).on('error', reject);
  });
}

// 主函数
async function main() {
  try {
    console.log('🔍 开始测试发布任务 #' + TASK_ID);
    console.log('=' .repeat(60));
    
    // 1. 测试代理
    const proxyResult = await testProxy();
    
    if (!proxyResult.success) {
      console.log('\n❌ 代理测试失败，请检查代理配置');
      return;
    }
    
    // 2. 测试发布
    // await testPublish();  // 暂时跳过，需要获取 Cookie
    
    console.log('\n✅ 测试完成');
    
  } catch (error) {
    console.error('\n❌ 测试失败:', error);
  }
}

main();
