#!/usr/bin/env node
/**
 * 测试直连模式发布 - Task #61
 * 不使用代理，配合反检测脚本
 */

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

const PYTHON_API = 'http://localhost:5005';
const TASK_ID = 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: false,  // 显示浏览器
  return_screenshot: true,
  user_id: 1,
  publish_task_id: TASK_ID,
  publish_account_id: 24,
  proxy: {
    enabled: false  // ⚠️ 关键：不使用代理，避免超时
  }
};

console.log('🎯 测试直连模式发布 - Task #' + TASK_ID);
console.log('='.repeat(60));
console.log('策略: 使用直连 + 反检测脚本');
console.log('原因: 神龙代理 IP 有效期仅 3 分钟，大文件上传会超时');
console.log('='.repeat(60));

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: 600000  // 10 分钟超时（大文件）
}, (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));
      
      if (result.screenshot_base64) {
        const screenshotPath = `E:\\Workspace\\multi-platform-media-manage\\server\\uploads\\screenshots\\direct_publish_${TASK_ID}_${Date.now()}.png`;
        fs.writeFileSync(screenshotPath, Buffer.from(result.screenshot_base64, 'base64'));
        console.log('\n📷 截图已保存:', screenshotPath);
      }
    } catch (e) {
      console.error('❌ 解析失败:', e);
      console.log('响应:', data.substring(0, 500));
    }
  });
});

req.on('error', (e) => console.error('❌ 请求失败:', e));
req.on('timeout', () => {
  console.error('❌ 请求超时（10分钟）');
  req.destroy();
});

req.write(postData);
req.end();

console.log('\n⏳ 发布中...（大文件上传需要较长时间）');
console.log('💡 可以在浏览器窗口观察进度');
