#!/usr/bin/env tsx
/**
 * 直接测试 Python API - 查看详细响应
 */
import { initDatabase } from '../models/index.js';
import { PlatformAccount } from '../models/entities/PlatformAccount.js';
import { AppDataSource } from '../models/index.js';
import { CookieManager } from '../automation/cookie.js';
import { logger } from '../utils/logger.js';

const PYTHON_SERVICE_URL = process.env.PYTHON_PUBLISH_SERVICE_URL || 'http://localhost:5005';

async function main() {
  logger.info('========================================');
  logger.info('直接测试 Python API - 查看详细响应');
  logger.info('========================================');

  await initDatabase();
  logger.info('数据库连接已初始化');

  const accountId = parseInt(process.argv[2] || '35');
  
  const accountRepository = AppDataSource.getRepository(PlatformAccount);
  const account = await accountRepository.findOne({
    where: {
      platform: 'xiaohongshu',
      id: accountId,
    },
  });

  if (!account) {
    logger.error(`未找到账号 ID: ${accountId}`);
    process.exit(1);
  }

  logger.info(`找到账号: ID=${account.id}, 名称=${account.accountName}`);

  if (!account.cookieData) {
    logger.error('账号没有 Cookie 数据');
    process.exit(1);
  }

  // 解密 Cookie
  let decryptedCookies: string;
  try {
    decryptedCookies = CookieManager.decrypt(account.cookieData);
    logger.info('Cookie 解密成功');
  } catch {
    decryptedCookies = account.cookieData;
    logger.info('使用原始 Cookie 数据');
  }

  // 解析 Cookie
  let cookieList: { name: string; value: string; domain: string; path: string }[];
  try {
    cookieList = JSON.parse(decryptedCookies);
    logger.info(`解析到 ${cookieList.length} 个 Cookie (JSON 格式)`);
  } catch {
    // 字符串格式
    cookieList = decryptedCookies.split(';').map(item => {
      const [name, value] = item.trim().split('=');
      return { name: name.trim(), value: (value || '').trim(), domain: '', path: '/' };
    }).filter(c => c.name);
    logger.info(`解析到 ${cookieList.length} 个 Cookie (字符串格式)`);
  }

  const cookieString = JSON.stringify(cookieList);
  logger.info(`Cookie JSON 长度: ${cookieString.length} 字符`);

  // 调用 Python API
  logger.info('\n========================================');
  logger.info('调用 Python API: /works');
  logger.info('========================================\n');

  try {
    const response = await fetch(`${PYTHON_SERVICE_URL}/works`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        platform: 'xiaohongshu',
        cookie: cookieString,
        page: 0,
        page_size: 20,
        auto_paging: true,
      }),
    });

    logger.info(`HTTP 状态码: ${response.status} ${response.statusText}`);

    const result = await response.json();
    
    logger.info('\n========================================');
    logger.info('Python API 响应:');
    logger.info('========================================');
    logger.info(`success: ${result.success}`);
    logger.info(`platform: ${result.platform}`);
    logger.info(`works count: ${result.works?.length || 0}`);
    logger.info(`total: ${result.total || 0}`);
    logger.info(`has_more: ${result.has_more}`);
    logger.info(`next_page: ${result.next_page}`);
    logger.info(`error: ${result.error || '(none)'}`);
    logger.info(`debug_info: ${result.debug_info || '(none)'}`);
    
    if (result.works && result.works.length > 0) {
      logger.info(`\n前 3 个作品:`);
      result.works.slice(0, 3).forEach((work: any, index: number) => {
        logger.info(`  ${index + 1}. ${work.title} (ID: ${work.work_id})`);
      });
    } else {
      logger.warn('\n⚠️ 没有获取到任何作品！');
    }

    logger.info('\n完整响应 JSON:');
    logger.info(JSON.stringify(result, null, 2));

  } catch (error) {
    logger.error('调用 Python API 失败:', error);
    if (error instanceof Error) {
      logger.error('错误堆栈:', error.stack);
    }
  }

  process.exit(0);
}

main();
