import { initDatabase } from '../models/index.js';
import { logger } from '../utils/logger.js';
import { WeixinVideoWorkStatisticsImportService } from '../services/WeixinVideoWorkStatisticsImportService.js';

/**
 * 用法: pnpm exec tsx server/src/scripts/run-weixin-video-work-stats-import.ts [accountId] [show]
 * 不传 accountId 则同步所有视频号账号
 * 第二个参数传 show 则打开浏览器可视模式，便于观察点击操作
 */
async function main() {
  try {
    await initDatabase();
    const accountIdArg = process.argv[2];
    const showArg = process.argv[3];
    const showBrowser = (showArg || '').toLowerCase() === 'show';
    if (accountIdArg) {
      const accountId = parseInt(accountIdArg, 10);
      if (isNaN(accountId)) {
        logger.error('[WX WorkStats] accountId 必须是数字');
        process.exit(1);
      }
      logger.info(`[WX WorkStats] 单账号同步 accountId=${accountId}${showBrowser ? ' (可视模式)' : ''} start...`);
      await WeixinVideoWorkStatisticsImportService.runDailyImportForAccount(accountId, showBrowser);
    } else {
      logger.info('[WX WorkStats] 全量同步 start...');
      await WeixinVideoWorkStatisticsImportService.runDailyImport();
    }
    logger.info('[WX WorkStats] Manual run done.');
    process.exit(0);
  } catch (e) {
    logger.error('[WX WorkStats] Manual run failed:', e);
    process.exit(1);
  }
}

void main();
