import { initDatabase, AppDataSource, PlatformAccount } from '../models/index.js';
import { logger } from '../utils/logger.js';
import { WorkService } from '../services/WorkService.js';

async function main() {
  const arg = process.argv[2];
  if (!arg) {
    logger.error('请提供账号（platform_accounts.id 或 account_id 字符串）');
    logger.info('用法: tsx src/scripts/sync-works-for-account.ts <6|dy_1742363409>');
    process.exit(1);
  }

  await initDatabase();
  const accountRepo = AppDataSource.getRepository(PlatformAccount);

  const maybeId = Number(arg);
  let account: PlatformAccount | null = null;
  if (!Number.isNaN(maybeId) && Number.isInteger(maybeId) && maybeId > 0) {
    account = await accountRepo.findOne({ where: { id: maybeId } });
  }
  if (!account) {
    account = await accountRepo.findOne({ where: { accountId: arg } });
  }

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

  logger.info(`准备同步账号: id=${account.id}, userId=${account.userId}, platform=${account.platform}, accountId=${account.accountId}`);

  const workService = new WorkService();
  const result = await workService.syncWorks(
    account.userId,
    account.id,
    undefined,
    (p, step) => logger.info(`[进度] ${p}% ${step}`)
  );

  logger.info(`同步完成: synced=${result.synced}, accounts=${result.accounts}`);
  logger.info(`账号摘要: ${JSON.stringify(result.accountSummaries, null, 2)}`);
  process.exit(0);
}

void main().catch((e) => {
  logger.error('执行失败:', e);
  process.exit(1);
});

