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 { CookieManager } from '../automation/cookie.js';
import { logger } from '../utils/logger.js';

async function testAllXhsAccounts() {
  try {
    await initDatabase();
    logger.info('数据库连接已初始化');

    // 获取所有小红书账号
    const accountRepository = AppDataSource.getRepository(PlatformAccount);
    const accounts = await accountRepository.find({
      where: { platform: 'xiaohongshu' },
      order: { id: 'ASC' }
    });

    if (accounts.length === 0) {
      logger.info('没有找到小红书账号');
      return;
    }

    logger.info(`\n${'='.repeat(60)}`);
    logger.info(`找到 ${accounts.length} 个小红书账号，开始批量测试...`);
    logger.info(`${'='.repeat(60)}\n`);

    const results: Array<{
      id: number;
      name: string;
      success: boolean;
      worksCount: number;
      error?: string;
    }> = [];

    const workService = new WorkService();

    for (let i = 0; i < accounts.length; i++) {
      const account = accounts[i];
        logger.info(`\n[${i + 1}/${accounts.length}] 测试账号: ID=${account.id}, 名称=${account.accountName}`);
        logger.info(`${'-'.repeat(60)}`);

        try {
          if (!account.cookieData) {
            logger.error('账号没有 Cookie 数据');
            results.push({
              id: account.id,
              name: account.accountName || '(未设置)',
              success: false,
              worksCount: 0,
              error: '账号没有 Cookie 数据'
            });
            continue;
          }

          // 调用同步方法
          const startTime = Date.now();
          await workService.syncAccountWorks(account.userId, account);
          const duration = ((Date.now() - startTime) / 1000).toFixed(2);

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

          logger.info(`✅ 成功: 获取到 ${worksCount} 个作品 (耗时: ${duration}秒)`);
          results.push({
            id: account.id,
            name: account.accountName || '(未设置)',
            success: true,
            worksCount: worksCount
          });
        } catch (error: any) {
          logger.error(`❌ 异常: ${error.message || error}`);
          results.push({
            id: account.id,
            name: account.accountName || '(未设置)',
            success: false,
            worksCount: 0,
            error: error.message || String(error)
          });
        }

      // 每个账号之间稍作延迟，避免请求过快
      if (i < accounts.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 2000));
      }
    }

    // 打印汇总结果
    logger.info(`\n${'='.repeat(60)}`);
    logger.info('测试结果汇总');
    logger.info(`${'='.repeat(60)}`);

    const successCount = results.filter(r => r.success).length;
    const failCount = results.filter(r => !r.success).length;
    const totalWorks = results.reduce((sum, r) => sum + r.worksCount, 0);

    logger.info(`总账号数: ${accounts.length}`);
    logger.info(`成功: ${successCount} 个`);
    logger.info(`失败: ${failCount} 个`);
    logger.info(`总作品数: ${totalWorks} 个`);
    logger.info(`\n详细结果:`);

    results.forEach((result, index) => {
      const status = result.success ? '✅' : '❌';
      logger.info(`${index + 1}. ${status} [ID: ${result.id}] ${result.name}: ${result.success ? `${result.worksCount} 个作品` : result.error}`);
    });

    if (failCount > 0) {
      logger.info(`\n失败的账号详情:`);
      results.filter(r => !r.success).forEach(result => {
        logger.info(`  - [ID: ${result.id}] ${result.name}: ${result.error}`);
      });
    }

    logger.info(`\n${'='.repeat(60)}\n`);

  } catch (error: any) {
    logger.error('批量测试失败:', error);
    process.exit(1);
  } finally {
    await AppDataSource.destroy();
    process.exit(0);
  }
}

testAllXhsAccounts().catch(console.error);
