/**
 * One-shot verify: 跑 chain-composer 对指定 patient, 打印各 chain 状态。
 * 用法:pnpm tsx src/cli/verify-chain.cli.ts --id=<patientId>
 */
import { NestFactory } from '@nestjs/core';
import { AppModule } from '../app.module';
import { PrismaService } from '../prisma/prisma.service';
import { ChainComposerService } from '../modules/plan/engine/chain-composer.service';

async function main() {
  const id = process.argv.find((a) => a.startsWith('--id='))?.slice('--id='.length);
  if (!id) {
    console.error('Usage: --id=<patientId>');
    process.exit(1);
  }
  const app = await NestFactory.createApplicationContext(AppModule, { logger: ['error'] });
  const prisma = app.get(PrismaService);
  const composer = app.get(ChainComposerService);
  const facts = await prisma.patientFact.findMany({
    where: { patientId: id, status: { in: ['active', 'fulfilled'] } },
    orderBy: { occurredAt: 'asc' },
  });
  const chains = composer.compose(facts as any);
  console.log(`\n=== Patient ${id} — ${chains.length} chains ===\n`);
  for (const c of chains) {
    const target = c.target ? ' ★' : '';
    console.log(
      `[${c.status.padEnd(11)}] stage=${c.currentStage} ${(c.name ?? '?').padEnd(18)} tooth=${c.toothPosition ?? '-'} code=${c.code ?? '-'} cat=${c.category}${target}`,
    );
    const lc = (c as { lifecycleNoteZh?: string }).lifecycleNoteZh;
    if (lc) console.log(`  lifecycle: ${lc}`);
    const nodes = (c as unknown as { nodes?: Array<{ stage?: number; title?: string; detail?: string; hint?: string; done?: boolean }> }).nodes;
    if (nodes && nodes.length) {
      for (const n of nodes) console.log(`    S${n.stage ?? '?'} ${n.done ? '✓' : '○'} ${n.title ?? ''} ${n.detail ? '· ' + n.detail : ''}${n.hint ? ' [' + n.hint + ']' : ''}`);
    }
    const altClosedBy = (c as { alternativeClosedBy?: string }).alternativeClosedBy;
    if (altClosedBy) console.log(`  alt-closed-by: ${altClosedBy}`);
  }
  await app.close();
}
main().catch((e) => { console.error(e); process.exit(1); });
