/**
 * Recompute Plans CLI — 批量跑 PlanEngine,产 FollowupPlan + PlanReason
 *
 * Usage:
 *   pnpm recompute-plans                   # 默认 host=demo
 *   pnpm recompute-plans -- --host=friday
 */
import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import { AppModule } from '../app.module';
import { PlanEngineService } from '../modules/plan/engine/plan-engine.service';
import { PrismaService } from '../prisma/prisma.service';

interface Args {
  host: string;
}

function parseArgs(argv: string[]): Args {
  const args: Args = { host: 'demo' };
  for (const a of argv) {
    if (a.startsWith('--host=')) args.host = a.slice('--host='.length);
  }
  return args;
}

async function bootstrap() {
  const args = parseArgs(process.argv.slice(2));
  const logger = new Logger('recompute-plans');
  const app = await NestFactory.createApplicationContext(AppModule, {
    logger: ['log', 'warn', 'error'],
  });

  try {
    const prisma = app.get(PrismaService);
    const engine = app.get(PlanEngineService);

    const host = await prisma.host.findUnique({ where: { name: args.host } });
    if (!host) throw new Error(`Host '${args.host}' not found`);
    // 取该 host 第一个 tenant(demo 场景固定一个)
    const tenants = await prisma.patient.findMany({
      where: { hostId: host.id },
      select: { tenantId: true },
      distinct: ['tenantId'],
    });
    if (tenants.length === 0) throw new Error('No tenants found for host');

    for (const t of tenants) {
      logger.log(`▶ Running engine for host=${args.host} tenant=${t.tenantId} ...`);
      const r = await engine.runAllForHost({
        hostId: host.id,
        tenantId: t.tenantId,
      });
      logger.log(`──────────────────────────────────────────────────────`);
      logger.log(`Result(${t.tenantId}):`);
      logger.log(`  scenariosRun:         ${r.scenariosRun}`);
      logger.log(`  patientsHit:          ${r.patientsHit}`);
      logger.log(`  plansCreated:         ${r.plansCreated}`);
      logger.log(`  plansSuperseded:      ${r.plansSuperseded}`);
      logger.log(`  plansUnchanged:       ${r.plansUnchanged}`);
      logger.log(`  plansSkippedAssigned: ${r.plansSkippedAssigned}`);
      logger.log(`  duration:             ${r.durationMs}ms`);
      logger.log(`──────────────────────────────────────────────────────`);
    }
  } catch (err) {
    new Logger('recompute-plans').error(err instanceof Error ? err.stack : String(err));
    process.exitCode = 2;
  } finally {
    await app.close();
  }
}

bootstrap().catch((err) => {
  console.error(err);
  process.exit(3);
});
