#!/usr/bin/env node
/**
 * 完整的发布测试 - Task #61
 * 使用增强的反检测功能和代理
 */

const http = require('http');
const fs = require('fs');
const path = require('path');

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

// Task #61 的完整数据
const PUBLISH_DATA = {
  platform: 'weixin',  // 微信视频号
  cookie: JSON.stringify([
    {
      "name":"sessionid",
      "value":"BgAAXERdxFp7jCFlOv26QpoGfHFTWafeI1UHi%2F6RxenyzR8zhCfVtyOkJFAw4UJD2yzCpzRQ3phKnIIRiNDY2eM6sUHMCtSAdlG4%2FEqu89Qb",
      "domain":"channels.weixin.qq.com",
      "path":"/",
      "expires":1806737620.630474,
      "httpOnly":false,
      "secure":true,
      "sameSite":"no_restriction"
    },
    {
      "name":"wxuin",
      "value":"197897203",
      "domain":"channels.weixin.qq.com",
      "path":"/",
      "expires":1806737620.630622,
      "httpOnly":false,
      "secure":true,
      "sameSite":"no_restriction"
    }
  ]),
  title: '拍照机',
  description: '拍照机',
  video_path: 'E:\\Workspace\\multi-platform-media-manage\\server\\uploads\\videos\\88ce3597-0499-4882-bcb5-b6d0722547af.mp4',
  tags: [],
  headless: true,  // 改回无头模式
  return_screenshot: true,
  user_id: 1,
  publish_task_id: TASK_ID,
  publish_account_id: 24,
  proxy: {
    enabled: true,
    provider: 'shenlong',
    productKey: 'o2ihwv3e',
    signature: 'ccff437b0c211d7a758b0926cbdcf958',
    regionCode: '310000',  // 上海
    city: '上海'
  }
};

// 检查视频文件
function checkVideoFile() {
  const videoPath = PUBLISH_DATA.video_path;
  console.log('\n📹 检查视频文件...');
  console.log('路径:', videoPath);
  
  if (!fs.existsSync(videoPath)) {
    console.error('❌ 视频文件不存在');
    return false;
  }
  
  const stats = fs.statSync(videoPath);
  console.log('✅ 文件大小:', (stats.size / 1024 / 1024).toFixed(2), 'MB');
  return true;
}

// 发布
function publish() {
  return new Promise((resolve, reject) => {
    console.log('\n🚀 开始发布...');
    console.log('平台:', PUBLISH_DATA.platform);
    console.log('标题:', PUBLISH_DATA.title);
    console.log('代理: 启用 (上海地区)');
    console.log('Headless:', PUBLISH_DATA.headless);
    
    const postData = JSON.stringify(PUBLISH_DATA);
    
    const req = http.request(`${PYTHON_API}/publish/ai-assisted`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': Buffer.byteLength(postData)
      },
      timeout: 180000  // 3分钟超时
    }, (res) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('end', () => {
        try {
          const result = JSON.parse(data);
          console.log('\n📊 发布结果:');
          console.log('成功:', result.success);
          console.log('状态:', result.status);
          console.log('错误:', result.error || '无');
          console.log('需要验证码:', result.need_captcha || false);
          console.log('验证码类型:', result.captcha_type || '无');
          
          if (result.screenshot_base64) {
            console.log('截图: 已获取 (长度:', result.screenshot_base64.length, ')');
            // 保存截图
            const screenshotPath = `E:\\Workspace\\multi-platform-media-manage\\uploads\\screenshots\\test_task_${TASK_ID}_${Date.now()}.png`;
            fs.writeFileSync(screenshotPath, Buffer.from(result.screenshot_base64, 'base64'));
            console.log('截图已保存:', screenshotPath);
          }
          
          if (result.video_url) {
            console.log('视频链接:', result.video_url);
          }
          
          resolve(result);
        } catch (e) {
          console.error('❌ 解析响应失败:', e);
          console.log('原始响应:', data.substring(0, 500));
          reject(e);
        }
      });
    });
    
    req.on('error', (e) => {
      console.error('❌ 请求失败:', e.message);
      reject(e);
    });
    
    req.on('timeout', () => {
      console.error('❌ 请求超时');
      req.destroy();
      reject(new Error('Timeout'));
    });
    
    req.write(postData);
    req.end();
  });
}

// 主函数
async function main() {
  try {
    console.log('🎯 完整发布测试 - Task #' + TASK_ID);
    console.log('='.repeat(60));
    
    // 1. 检查视频文件
    if (!checkVideoFile()) {
      return;
    }
    
    // 2. 发布
    const result = await publish();
    
    console.log('\n' + '='.repeat(60));
    if (result.success) {
      console.log('✅ 发布成功！');
    } else if (result.need_captcha) {
      console.log('⚠️  需要验证码:', result.captcha_type);
      console.log('💡 建议: 在有头浏览器模式下处理验证码');
    } else {
      console.log('❌ 发布失败');
      console.log('💡 建议: 检查 Cookie 是否有效，或查看截图分析原因');
    }
    
  } catch (error) {
    console.error('\n❌ 测试失败:', error);
  }
}

main();
