const { PrismaClient } = require('@prisma/client');
const p = new PrismaClient();
(async () => {
  const patient = await p.patient.findFirst({ where: { externalId: '2139753' } });
  console.log(`═══ PAC · 1. 患者主档 ═══`);
  console.log(`  ${patient.name} (${patient.externalId})  tenant=${patient.tenantId.slice(0,8)}...`);

  // PAC 诊断
  const dx = await p.patientFact.findMany({
    where: { patientId: patient.id, type: 'diagnosis_record', status: 'active' },
    select: { content: true, occurredAt: true },
    orderBy: { occurredAt: 'asc' },
  });
  console.log(`\n═══ PAC · 2. 诊断 fact (${dx.length} 条) ═══`);
  for (const f of dx) {
    console.log(`  ${f.content.code} tooth=${f.content.tooth_position||'-'}  ${f.occurredAt?.toISOString().slice(0,10)}  · ${f.content.name_zh||''}`);
  }

  // PAC 已做治疗
  const actual = await p.patientFact.findMany({
    where: { patientId: patient.id, type: 'treatment_record', kind: 'actual', status: { in: ['active','fulfilled'] } },
    select: { content: true, occurredAt: true },
  });
  const cats = {};
  for (const f of actual) cats[f.content.category] = (cats[f.content.category]||0)+1;
  console.log(`\n═══ PAC · 3. 已做治疗 actual (${actual.length} 条) ═══`);
  console.log('  by category:', cats);

  // 计划治疗
  const planned = await p.patientFact.findMany({
    where: { patientId: patient.id, type: 'treatment_record', kind: 'planned', status: 'active' },
    select: { content: true },
  });
  const pcats = {};
  for (const f of planned) pcats[f.content.category] = (pcats[f.content.category]||0)+1;
  console.log(`\n═══ PAC · 4. 计划治疗 planned (${planned.length} 条) ═══`);
  console.log('  by category:', pcats);

  // chain-composer 推断潜在新链
  const DX_TO_CAT = {
    K02:['restorative'], K04:['endodontic'], K05:['periodontic'],
    K08:['implant','prosthodontic'],
    IMPLANT_RECOMMENDED:['implant'], CROWN_RECOMMENDED:['prosthodontic'],
    FILLING_RECOMMENDED:['restorative'], SRP_RECOMMENDED:['periodontic'],
  };
  const earliestByKey = new Map();
  for (const sig of dx) {
    const c = sig.content;
    const code = c.code; const tooth = String(c.tooth_position||'');
    const exp = DX_TO_CAT[code]; if (!exp) continue;
    if (exp.some(cat => cats[cat])) continue;
    const key = `${code}|${tooth.trim()}`;
    const prev = earliestByKey.get(key);
    if (!prev || (sig.occurredAt && (!prev.occurredAt || sig.occurredAt < prev.occurredAt))) {
      earliestByKey.set(key, sig);
    }
  }
  const chains = [...earliestByKey.values()]
    .map(s => ({...s, gap: s.occurredAt ? Math.floor((Date.now()-s.occurredAt)/86400_000) : 0 }))
    .sort((a,b) => b.gap - a.gap);
  console.log(`\n═══ PAC · 5. 推断潜在新链 = ${chains.length} 条 ═══`);
  for (const c of chains) {
    console.log(`  ⭐ ${c.content.code}  tooth=${c.content.tooth_position||'-'}  ${c.gap} 天断口  (诊于 ${c.occurredAt?.toISOString().slice(0,10)})  → ${DX_TO_CAT[c.content.code].join('/')}`);
  }

  // Plan + breakdown
  const plan = await p.followupPlan.findFirst({
    where: { patientId: patient.id, status: 'active' },
    include: { reasons: true },
  });
  console.log(`\n═══ PAC · 6. 召回 plan ═══`);
  if (plan) {
    console.log(`  ${plan.priorityScore} 分  goal=${plan.goal?.slice(0,30)}...`);
    console.log(`  breakdown:`, JSON.stringify(plan.reasons[0]?.breakdown).slice(0,200));
  }
  await p.$disconnect();
})();
