/**
 * Stale Scan CLI — 手动触发凌晨兜底扫描。
 *
 * 找出"画像 stale"的患者(persona.eventWatermark < max(transaction.eventSeq) 或没 persona),
 * 入 persona-recompute 队列(jobId 自动去重)。
 *
 * Usage:
 *   pnpm stale-scan
 *
 * 生产上自动每天 02:00 跑(StaleScanService.@Cron),本 CLI 是运维手动入口。
 */
import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import { AppModule } from '../app.module';
import { StaleScanService } from '../queues/stale-scan.service';

async function main(): Promise<void> {
  const logger = new Logger('stale-scan-cli');
  const app = await NestFactory.createApplicationContext(AppModule, { logger });

  try {
    const svc = app.get(StaleScanService);
    logger.log('Running stale scan...');
    const r = await svc.runNow();
    logger.log(
      `Done. stale=${r.stale} enqueued=${r.enqueued} failed=${r.failed}`,
    );
  } finally {
    await app.close();
  }
}

main().catch((err) => {
  const e = err instanceof Error ? err : new Error(String(err));
  // eslint-disable-next-line no-console
  console.error('stale-scan CLI failed:', e.message, e.stack);
  process.exit(1);
});
