#!/usr/bin/env tsx
/**
 * 测试小红书作品同步 - 用于测试自动分页逻辑
 * 
 * 运行: cd server && pnpm exec tsx src/scripts/test-xhs-works-sync.ts "O_O点心时间到了"
 */
import { initDatabase } from '../models/index.js';
import { PlatformAccount } from '../models/entities/PlatformAccount.js';
import { AppDataSource } from '../models/index.js';
import { WorkService } from '../services/WorkService.js';
import { logger } from '../utils/logger.js';
import { CookieManager } from '../automation/cookie.js';
import type { PlatformType } from '@media-manager/shared';

async function main() {
  logger.info('========================================');
  logger.info('测试小红书作品同步 - 自动分页统计');
  logger.info('========================================');

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

  const accountArg = process.argv[2];
  if (!accountArg) {
    console.log('\n用法: pnpm exec tsx src/scripts/test-xhs-works-sync.ts <账号ID或账号名称>');
    console.log('\n示例: pnpm exec tsx src/scripts/test-xhs-works-sync.ts 35');
    console.log('示例: pnpm exec tsx src/scripts/test-xhs-works-sync.ts "O_O点心时间到了"');
    console.log('\n正在列出所有小红书账号...\n');
    
    // 列出所有小红书账号
    const accountRepository = AppDataSource.getRepository(PlatformAccount);
    const accounts = await accountRepository.find({
      where: { platform: 'xiaohongshu' },
      order: { id: 'ASC' },
    });
    
    if (accounts.length === 0) {
      logger.error('未找到任何小红书账号');
      process.exit(1);
    }
    
    console.log('小红书账号列表:');
    accounts.forEach(acc => {
      console.log(`  ID: ${acc.id}, 名称: ${acc.accountName || '(未设置)'}, 作品数: ${acc.worksCount}`);
    });
    console.log('');
    process.exit(0);
  }

  try {
    // 查找账号 - 先尝试按ID查找，再按名称查找
    const accountRepository = AppDataSource.getRepository(PlatformAccount);
    let account: PlatformAccount | null = null;
    
    const accountId = parseInt(accountArg);
    if (!isNaN(accountId)) {
      // 按ID查找
      account = await accountRepository.findOne({
        where: {
          platform: 'xiaohongshu',
          id: accountId,
        },
      });
    }
    
    if (!account) {
      // 按名称查找
      account = await accountRepository.findOne({
        where: {
          platform: 'xiaohongshu',
          accountName: accountArg,
        },
      });
    }

    if (!account) {
      logger.error(`未找到账号: ${accountArg}`);
      logger.info('提示: 可以不带参数运行脚本查看所有账号列表');
      process.exit(1);
    }

    logger.info(`找到账号: ID=${account.id}, 名称=${account.accountName}, 平台=${account.platform}`);
    logger.info(`账号信息: 粉丝数=${account.fansCount}, 作品数=${account.worksCount}`);

    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 数据');
    }

    // 调用作品同步
    logger.info('\n========================================');
    logger.info('开始同步作品（将显示详细分页日志）...');
    logger.info('========================================\n');

    const workService = new WorkService();
    await workService.syncAccountWorks(account.userId, account);

    logger.info('\n========================================');
    logger.info('作品同步完成！');
    logger.info('========================================');

    // 查询同步后的作品数量
    const { Work } = await import('../models/entities/Work.js');
    const workRepository = AppDataSource.getRepository(Work);
    const worksCount = await workRepository.count({
      where: {
        accountId: account.id,
      },
    });

    logger.info(`账号 ${account.accountName} 当前数据库中的作品数: ${worksCount}`);
  } catch (error) {
    logger.error('测试失败:', error);
    if (error instanceof Error) {
      logger.error('错误堆栈:', error.stack);
    }
    process.exit(1);
  }

  process.exit(0);
}

main();
