import {
  Injectable,
  Logger,
  NotFoundException,
  BadRequestException,
  ForbiddenException,
} from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import {
  Permission,
  PlanEventType,
  planScenarioLabel,
  subLabelZh,
  applyLiveDays,
  type ListPlansResponse,
  type PlanCountsResponse,
  type PlanDetailResponse,
  type PlanReasonBrief,
} from '@pac/types';
import { calcAge, maskName, maskPhone } from '@pac/utils';
import { PrismaService } from '../../prisma/prisma.service';
import { recordPlanEvent, computeHeldSeconds } from './plan-event.recorder';
import { PERSONA_TAG_FILTER_DIMS, parsePersonaTags } from '@pac/types';
import type { TenantScopeContext } from '../../common/decorators/tenant-scope.decorator';
import type { PlanEngineService } from './engine/plan-engine.service';
import type {
  ListPlansQueryDto,
  SubmitExecutionRequestDto,
} from './dto/plan.dto';
import { PriorityDistributionService } from './priority-distribution.service';
import { ExecutionService } from './execution.service';
import { renderAgentIdentity } from '../ai/calls/draft-plan-script/shared/agent-identity';
import type { ScriptAgentIdentity } from '../ai/calls/draft-plan-script/shared/agent-identity';

/**
 * PlanService — Plan 维度 CRUD(list / detail / assign / recycle / recompute / submitExecution)
 *
 * 跟 ExecutionService 分工:
 *   - PlanService: plan 的查询 + 生命周期(assign/recycle)+ 触发重算
 *   - ExecutionService: 客服回写 execution 行 + 状态机 + 熔断(plan.submitExecution 委托过去)
 *
 * 注:demo 路径不走本服务(走 PlanAggregateService 聚合),本服务用于真实工作台 CRUD
 */

const RECYCLE_TIMEOUT_HOURS = 24; // assignment 后 24h 未结案自动回收(后续接 tenant 配置)

/** 召回池数字概览(queueStats 返回;MCP recall_queue_stats / 工作台 KPI 共用)。 */
export interface PlanQueueStatsResponse {
  view: string;
  total: number;
  /** 优先级分档:high ≥70 / mid 40–69 / low <40 */
  byPriority: { high: number; mid: number; low: number };
  /** 按病种(sub_scenario)分布,信号(reason)条数倒序 */
  byScenario: Array<{ scenario: string; subScenario: string; label: string; signals: number }>;
}

@Injectable()
export class PlanService {
  private readonly logger = new Logger(PlanService.name);

  constructor(
    private readonly prisma: PrismaService,
    private readonly executions: ExecutionService,
    private readonly priorityDist: PriorityDistributionService,
  ) {}

  // ─────────────────────────────────────────────
  // list
  // ─────────────────────────────────────────────

  async list(
    scope: TenantScopeContext,
    query: ListPlansQueryDto,
    permissions: readonly string[],
  ): Promise<ListPlansResponse> {
    const where = this.buildListWhere(scope, query, permissions);

    // W3 末:服务端 sort —— 替代前端 .sort,跨页排序正确
    const orderBy: Prisma.FollowupPlanOrderByWithRelationInput[] =
      query.sort === 'priority_asc'
        ? [{ priorityScore: 'asc' }, { createdAt: 'asc' }]
        : query.sort === 'created_desc'
          ? [{ createdAt: 'desc' }]
          : [{ priorityScore: 'desc' }, { createdAt: 'asc' }]; // priority_desc 默认

    const skip = (query.page - 1) * query.pageSize;
    const [total, rows] = await Promise.all([
      this.prisma.followupPlan.count({ where }),
      this.prisma.followupPlan.findMany({
        where,
        include: { reasons: { orderBy: { priorityScore: 'desc' } } },
        orderBy,
        skip,
        take: query.pageSize,
      }),
    ]);

    // 批量拉患者简介(列表展示用,避免每行单查)
    const patientIds = Array.from(new Set(rows.map((r) => r.patientId)));
    const patients = patientIds.length > 0
      ? await this.prisma.patient.findMany({
          where: { id: { in: patientIds } },
          select: {
            id: true,
            externalId: true,
            name: true,
            phone: true,
            phoneVerified: true,
            gender: true,
            birthDate: true,
          },
        })
      : [];
    const patientById = new Map(patients.map((p) => [p.id, p]));

    // 每个 plan 最近一次执行结果(左栏「成功/不成功/保持」角标用)。
    // 本页 plan 数少(≤pageSize),执行记录也少;一次拉齐后 JS 取每 plan 最新一条。
    const planIds = rows.map((r) => r.id);
    const execs = planIds.length > 0
      ? await this.prisma.planExecution.findMany({
          where: { planId: { in: planIds } },
          select: { planId: true, outcome: true },
          orderBy: { createdAt: 'desc' },
        })
      : [];
    const lastOutcomeByPlan = new Map<string, string>();
    for (const e of execs) {
      if (!lastOutcomeByPlan.has(e.planId)) lastOutcomeByPlan.set(e.planId, e.outcome);
    }

    // 池内百分位:租户级直方图缓存,算分位纯内存(见 PriorityDistributionService)。
    // 一页只查一次分布,不是每行一次。
    const pct = await Promise.all(
      rows.map((p) => this.priorityDist.percentileOf(scope.hostId, scope.tenantId, p.priorityScore)),
    );

    return {
      items: rows.map((p, i) => {
        const base = { ...serializePlan(p), priorityPercentile: pct[i] ?? null };
        const patient = patientById.get(p.patientId);
        return {
          ...base,
          scenarioLabel: planScenarioLabel(base.scenario),
          lastOutcome: (lastOutcomeByPlan.get(p.id) ?? null) as ListPlansResponse['items'][number]['lastOutcome'],
          patient: {
            externalId: patient?.externalId ?? '',
            /// name 原值透出(权限内可见);nameMasked 保留作脱敏视图兜底
            name: patient?.name ?? null,
            nameMasked: maskName(patient?.name ?? null),
            phoneMasked: maskPhone(patient?.phone ?? null),
            phoneVerified: patient?.phoneVerified ?? false,
            gender: patient?.gender ?? null,
            age: patient?.birthDate ? calcAge(patient.birthDate) : null,
          },
          /// reasons 透 signals JSON,前端 ReasonLine 用字典翻译富文本(跟详情页同源)
          reasons: p.reasons.map(toPlanReasonBrief),
        };
      }),
      page: query.page,
      pageSize: query.pageSize,
      total,
    };
  }

  // ─────────────────────────────────────────────
  // buildListWhere — list / queueStats 共用的 where 构造(view + 显式 filter + clinic 隔离 + persona 圈人)
  // ─────────────────────────────────────────────

  private buildListWhere(
    scope: TenantScopeContext,
    query: ListPlansQueryDto,
    permissions: readonly string[],
  ): Prisma.FollowupPlanWhereInput {
    const where: Prisma.FollowupPlanWhereInput = {
      hostId: scope.hostId,
      tenantId: scope.tenantId,
      supersededAt: null,
      // 集团模型:数据范围按品牌圈(plan→patient.sourceUnit);覆盖召回池 NULL-clinic 工单。
      // sourceUnits 空 = 不限品牌(集团级角色)。
      ...(scope.sourceUnits.length
        ? { patient: { sourceUnit: { in: scope.sourceUnits } } }
        : {}),
    };

    // view 基础过滤
    const view = query.view ?? 'mine';
    if (view === 'pool') {
      where.status = 'active';
      where.assigneeUserId = null;
      // 回访调度:snooze 未到期的不进召回池(约定回访 / 考虑中 / 近期不考虑 等到点自动浮现)。
      //   仅作用于 pool 视图 — 'mine' 仍展示我 snooze 的工单(客服看得到自己的回访安排)。
      where.AND = [
        { OR: [{ snoozedUntil: null }, { snoozedUntil: { lte: new Date() } }] },
      ];
    } else if (view === 'mine') {
      // "全部我的" = 我名下所有状态(active/assigned/completed/abandoned);
      // 具体状态由前端「进行中 / 已完成 / 已放弃」子 tab 通过 query.status 显式过滤。
      // (结案现在保留 assignee,所以"已完成"能查到。)
      where.assigneeUserId = scope.userId;
    } else if (view === 'all') {
      if (!permissions.includes(Permission.PLAN_VIEW_ALL)) {
        throw new ForbiddenException('需要 PLAN_VIEW_ALL 权限才能查看全部');
      }
    }

    // 显式 filter(覆盖 view 推断)
    if (query.status) where.status = query.status;
    // 诊所过滤:多选优先(IN),否则单选。staff 仍受下方 clinic 隔离 OR 约束(取交集)。
    if (query.targetClinicIds?.length) where.targetClinicId = { in: query.targetClinicIds };
    else if (query.targetClinicId) where.targetClinicId = query.targetClinicId;
    if (query.assigneeUserId) where.assigneeUserId = query.assigneeUserId;
    if (query.scenario) {
      where.reasons = { some: { scenario: query.scenario } };
    }

    // clinic 隔离:orgScope→clinicIds 是硬边界,始终生效(不按 view=all/PLAN_VIEW_ALL 豁免)。
    //   view=all 只是"看本 scope 内所有经办人",不跨 orgScope 诊所;宽 scope(集团 leader/admin)
    //   clinicIds 覆盖全部 → 此过滤为 no-op,不影响其看全量。窄 scope 才被真正圈住(修越权)。
    if (scope.clinicIds.length > 0) {
      where.OR = [
        { targetClinicId: { in: scope.clinicIds } },
        { targetClinicId: null },
      ];
    }

    // W3 末:服务端 keyword 模糊匹配 — patient.name / phone / 病历号 / externalId 任一命中
    // (替代前端本页 .filter,改成跨全表搜索,真实接入万人级数据后才能用)
    //   medicalRecordNumber = 病历号(客服可读档案号,如 "BA43016")— 列表搜索占位符标的就是它;
    //   externalId = host 内部业务 id(对人无意义),保留兜底,不删。
    const patientWhere: Prisma.PatientWhereInput = {};
    if (query.keyword) {
      patientWhere.OR = [
        { name: { contains: query.keyword, mode: 'insensitive' } },
        { phone: { contains: query.keyword } },
        { medicalRecordNumber: { contains: query.keyword, mode: 'insensitive' } },
        { externalId: { contains: query.keyword, mode: 'insensitive' } },
      ];
    }
    // 只看真实号码(外部对照表核实过的;测试库其余为造数假号)
    if (query.phoneVerified !== undefined) {
      patientWhere.phoneVerified = query.phoneVerified;
    }

    // 画像标签筛选:匹配患者**当前版**画像(supersededAt IS NULL)的 features。
    // 同一维度多选 = OR(该 feature 的 data 值命中任一);跨维度 = AND(每个维度各自 some)。
    // 维度/取值/data 路径以 PERSONA_TAG_FILTER_DIMS 为单一真理源(非法 key/value 静默丢弃)。
    if (query.personaTags) {
      const byKey = new Map<string, string[]>();
      for (const { key, value } of parsePersonaTags(query.personaTags)) {
        const dim = PERSONA_TAG_FILTER_DIMS.find((d) => d.key === key);
        if (!dim || !dim.options.some((o) => o.value === value)) continue;
        const arr = byKey.get(key) ?? [];
        arr.push(value);
        byKey.set(key, arr);
      }
      const personaConds: Prisma.PatientWhereInput[] = [];
      for (const [key, values] of byKey) {
        const dim = PERSONA_TAG_FILTER_DIMS.find((d) => d.key === key)!;
        const valueConds = values.map((v) =>
          dim.isArray
            ? { data: { path: [dim.dataPath], array_contains: v } }
            : { data: { path: [dim.dataPath], equals: v } },
        );
        personaConds.push({
          personas: {
            some: {
              supersededAt: null,
              features: { some: { key, OR: valueConds } },
            },
          },
        });
      }
      if (personaConds.length > 0) {
        patientWhere.AND = [...((patientWhere.AND as Prisma.PatientWhereInput[]) ?? []), ...personaConds];
      }
    }

    if (Object.keys(patientWhere).length > 0) {
      where.patient = patientWhere;
    }

    return where;
  }

  // ─────────────────────────────────────────────
  // queueStats — 召回池数字概览(总量 + 优先级分档 + 病种 breakdown)。
  //   复用 buildListWhere,所以 list 的全部筛选(view / scenario / personaTags 圈人 / clinic)都生效。
  //   "今日推荐" 的聚合输入:LLM 可先看 stats 给摘要,再用 list_recall_queue 取明细。
  //   注:byScenario 计的是 reason(信号)条数,非去重患者数(一患者多牙位 = 多 reason)。
  // ─────────────────────────────────────────────

  async queueStats(
    scope: TenantScopeContext,
    query: ListPlansQueryDto,
    permissions: readonly string[],
  ): Promise<PlanQueueStatsResponse> {
    // 默认 pool 视图(今日推荐场景);调用方可显式传 mine。
    const where = this.buildListWhere(
      scope,
      { ...query, view: query.view ?? 'pool' } as ListPlansQueryDto,
      permissions,
    );

    const [total, high, mid, low, reasonGroups] = await Promise.all([
      this.prisma.followupPlan.count({ where }),
      this.prisma.followupPlan.count({ where: { ...where, priorityScore: { gte: 70 } } }),
      this.prisma.followupPlan.count({ where: { ...where, priorityScore: { gte: 40, lt: 70 } } }),
      this.prisma.followupPlan.count({ where: { ...where, priorityScore: { lt: 40 } } }),
      this.prisma.planReason.groupBy({
        by: ['scenario', 'subKey'],
        where: { plan: where },
        _count: { _all: true },
      }),
    ]);

    // 按 sub_scenario(sub_key 的 '@' 前缀)归并,跨牙位累加信号数。
    const bucket = new Map<string, { scenario: string; subScenario: string; label: string; signals: number }>();
    for (const g of reasonGroups) {
      const subScenario = (g.subKey ?? '').split('@')[0] || g.scenario;
      const k = `${g.scenario}::${subScenario}`;
      const prev = bucket.get(k);
      bucket.set(k, {
        scenario: g.scenario,
        subScenario,
        label: subLabelZh(g.scenario, subScenario),
        signals: (prev?.signals ?? 0) + g._count._all,
      });
    }
    const byScenario = [...bucket.values()].sort((a, b) => b.signals - a.signals);

    return {
      view: query.view ?? 'pool',
      total,
      byPriority: { high, mid, low },
      byScenario,
    };
  }

  // ─────────────────────────────────────────────
  // counts — KPI / Tab badge 聚合(一次 SQL 5 个 count,避免前端 5 个并发 list 请求)
  // ─────────────────────────────────────────────

  async counts(
    scope: TenantScopeContext,
    permissions: readonly string[],
  ): Promise<PlanCountsResponse> {
    const base: Prisma.FollowupPlanWhereInput = {
      hostId: scope.hostId,
      tenantId: scope.tenantId,
      supersededAt: null,
    };
    // staff 受 clinic 隔离(跟 list 同口径)
    const clinicScope: Prisma.FollowupPlanWhereInput =
      scope.clinicIds.length > 0
        ? { OR: [{ targetClinicId: { in: scope.clinicIds } }, { targetClinicId: null }] }
        : {};
    const canViewAll = permissions.includes(Permission.PLAN_VIEW_ALL);

    const [mine, mineAssigned, mineCompleted, pool, all] = await Promise.all([
      this.prisma.followupPlan.count({
        where: { ...base, assigneeUserId: scope.userId, ...clinicScope },
      }),
      this.prisma.followupPlan.count({
        where: { ...base, assigneeUserId: scope.userId, status: 'assigned', ...clinicScope },
      }),
      this.prisma.followupPlan.count({
        where: { ...base, assigneeUserId: scope.userId, status: 'completed', ...clinicScope },
      }),
      this.prisma.followupPlan.count({
        where: { ...base, status: 'active', assigneeUserId: null, ...clinicScope },
      }),
      canViewAll
        ? this.prisma.followupPlan.count({ where: base })
        : Promise.resolve(0),
    ]);
    return { mine, mineAssigned, mineCompleted, pool, all };
  }

  // ─────────────────────────────────────────────
  // detail
  // ─────────────────────────────────────────────

  async detail(
    scope: TenantScopeContext,
    planId: string,
    /** 当前登录客服 —— 话术【回访客服】占位按它回填;缺省 → 通用"客服" */
    agent?: ScriptAgentIdentity,
  ): Promise<PlanDetailResponse> {
    const plan = await this.prisma.followupPlan.findFirst({
      // 集团模型:by-id 取 plan 也按品牌圈(plan→patient.sourceUnit);命中不到→下方 NotFound
      where: {
        id: planId,
        ...(scope.sourceUnits.length ? { patient: { sourceUnit: { in: scope.sourceUnits } } } : {}),
      },
      include: { reasons: { orderBy: { priorityScore: 'desc' } } },
    });
    if (!plan || plan.hostId !== scope.hostId || plan.tenantId !== scope.tenantId) {
      throw new NotFoundException(`Plan ${planId} not found`);
    }
    // clinic 隔离:与 list 一致 —— orgScope→clinicIds 硬边界,目标诊所须在 clinicIds 内或为 null(集团池)。
    //   否则按 ID 直取也不可见 —— 修切诊所后残留旧 URL 越权看别诊所患者(view_all 不豁免,详见 list)。
    if (
      scope.clinicIds.length > 0 &&
      plan.targetClinicId &&
      !scope.clinicIds.includes(plan.targetClinicId)
    ) {
      throw new NotFoundException(`Plan ${planId} not found`);
    }

    const [patient, persona, scriptRow, summariesRows, executions] = await Promise.all([
      this.prisma.patient.findUnique({
        where: { id: plan.patientId },
        include: { profile: true },
      }),
      this.prisma.persona.findFirst({
        where: { patientId: plan.patientId, supersededAt: null },
        include: { features: true },
        orderBy: { version: 'desc' },
      }),
      this.prisma.planScript.findUnique({ where: { planId: plan.id } }),
      this.prisma.planSummary.findMany({ where: { planId: plan.id } }),
      this.prisma.planExecution.findMany({
        where: { planId: plan.id },
        orderBy: { createdAt: 'desc' },
      }),
    ]);

    if (!patient) throw new NotFoundException(`Patient ${plan.patientId} not found`);

    return {
      plan: {
        ...serializePlan(plan),
        priorityPercentile: await this.priorityDist.percentileOf(
          scope.hostId,
          scope.tenantId,
          plan.priorityScore,
        ),
      },
      patient: serializePatient(patient),
      persona: persona ? serializePersona(persona) : null,
      // 落库正文的自报家门是占位符,读出来按当前登录人回填(见 agent-identity.ts)
      script: scriptRow
        ? serializeScript({ ...scriptRow, content: renderAgentIdentity(scriptRow.content, agent) })
        : null,
      summaries: summariesRows.map(serializeSummary),
      executions: executions.map(serializeExecution),
      evidence: computePlanEvidence(plan, persona),
    };
  }

  // ─────────────────────────────────────────────
  // assign
  // ─────────────────────────────────────────────

  /**
   * @param actorUserId 执行本次分配的人(从 token 取)。自认领时 = assigneeUserId;
   *   门诊经理指派他人时二者不同 —— 账本据此区分 claim / assign,
   *   这是 followup_plans 那两列(只存归属结果)永远表达不了的。
   */
  async assign(
    scope: TenantScopeContext,
    planId: string,
    assigneeUserId: string,
    actorUserId?: string,
  ): Promise<void> {
    const plan = await this.prisma.followupPlan.findFirst({
      where: {
        id: planId,
        ...(scope.sourceUnits.length ? { patient: { sourceUnit: { in: scope.sourceUnits } } } : {}),
      },
      select: {
        id: true, hostId: true, tenantId: true, status: true,
        assigneeUserId: true, patientId: true,
      },
    });
    if (!plan || plan.hostId !== scope.hostId || plan.tenantId !== scope.tenantId) {
      throw new NotFoundException(`Plan ${planId} not found`);
    }
    if (plan.status === 'completed' || plan.status === 'abandoned' || plan.status === 'superseded') {
      throw new BadRequestException(`Plan 已终态(${plan.status}),不能分配`);
    }
    if (plan.status === 'assigned' && plan.assigneeUserId !== assigneeUserId) {
      throw new BadRequestException(`Plan 已分配给 ${plan.assigneeUserId};回收后再分配`);
    }
    // 幂等:重复分配给同一人 → 只刷新 recycleAt
    const now = new Date();
    const isRepeat = plan.assigneeUserId === assigneeUserId;
    await this.prisma.$transaction(async (tx) => {
      await tx.followupPlan.update({
        where: { id: planId },
        data: {
          status: 'assigned',
          assigneeUserId,
          assignedAt: now,
          recycleAt: new Date(now.getTime() + RECYCLE_TIMEOUT_HOURS * 3600 * 1000),
        },
      });
      // 生命周期事件账本(append-only,收录边界见 PlanEventLog 注释)。
      // 幂等重复分配不记账 —— 那是同一次归属的续期,不是新的归属变更。
      if (!isRepeat) {
        await recordPlanEvent(tx, {
          hostId: plan.hostId,
          tenantId: plan.tenantId,
          planId: plan.id,
          patientId: plan.patientId,
          // actor 未知(老调用方没传)时按自认领记 —— 当前前端只有认领一条路径
          event:
            !actorUserId || actorUserId === assigneeUserId
              ? PlanEventType.CLAIM
              : PlanEventType.ASSIGN,
          assigneeUserId,
          actorUserId: actorUserId ?? assigneeUserId,
        });
      }
    });
  }

  // ─────────────────────────────────────────────
  // recycle
  // ─────────────────────────────────────────────

  async recycle(scope: TenantScopeContext, planId: string, actorUserId?: string): Promise<void> {
    const plan = await this.prisma.followupPlan.findFirst({
      where: {
        id: planId,
        ...(scope.sourceUnits.length ? { patient: { sourceUnit: { in: scope.sourceUnits } } } : {}),
      },
      select: {
        id: true, hostId: true, tenantId: true, status: true,
        assigneeUserId: true, assignedAt: true, patientId: true,
      },
    });
    if (!plan || plan.hostId !== scope.hostId || plan.tenantId !== scope.tenantId) {
      throw new NotFoundException(`Plan ${planId} not found`);
    }
    // 只拒终态(已完成/已放弃/已被取代);assigned 与 active 都可返池(无自动回收机制后,
    //   plan 可能停在 active 但仍挂在某客服名下 → 也要能退回池)。终态返池无意义,拒绝。
    if (plan.status === 'completed' || plan.status === 'abandoned' || plan.status === 'superseded') {
      throw new BadRequestException(`Plan 已终态(${plan.status}),不能返池`);
    }
    // 只在**确实挂着人**时记账:active 且无 assignee 的"返池"是空操作,记了是噪声
    const hadAssignee = plan.assigneeUserId != null;
    // ⭐ 在清空 assignedAt 之前算(见 computeHeldSeconds 注释)
    const heldSeconds = computeHeldSeconds(plan.assignedAt, new Date());
    await this.prisma.$transaction(async (tx) => {
      await tx.followupPlan.update({
        where: { id: planId },
        data: {
          status: 'active',
          assigneeUserId: null,
          assignedAt: null,
          recycleAt: null,
        },
      });
      if (hadAssignee) {
        await recordPlanEvent(tx, {
          hostId: plan.hostId,
          tenantId: plan.tenantId,
          planId: plan.id,
          patientId: plan.patientId,
          event: PlanEventType.RELEASE,
          assigneeUserId: null, // 释放后无人归属
          actorUserId: actorUserId ?? null,
          heldSeconds,
        });
      }
    });
  }

  // ─────────────────────────────────────────────
  // submitExecution(委托 ExecutionService)
  // ─────────────────────────────────────────────

  async submitExecution(
    scope: TenantScopeContext,
    planId: string,
    operatorUserId: string,
    dto: SubmitExecutionRequestDto,
  ): Promise<{
    executionId: string;
    planStatus: string;
    contactAttempts: number;
    breakerTripped: boolean;
  }> {
    // 直接透传 ExecutionService.submit 的富 shape(含 planStatus / 熔断状态),前端要这些字段
    return this.executions.submit(scope, planId, operatorUserId, dto);
  }

  async listExecutions(scope: TenantScopeContext, planId: string) {
    return { items: await this.executions.list(scope, planId) };
  }

  // ─────────────────────────────────────────────
  // recomputeByPatient(纯规则重算,不 pull host)
  // ─────────────────────────────────────────────

  async recomputeByPatient(
    scope: TenantScopeContext,
    patientId: string,
    engine: PlanEngineService,
  ): Promise<{ plansCreated: number }> {
    const patient = await this.prisma.patient.findFirst({
      where: {
        hostId: scope.hostId,
        tenantId: scope.tenantId,
        id: patientId,
        // 品牌隔离:与其它 by-id 守卫对齐,防跨品牌触发重算 + 借计数差做存在性探测
        ...(scope.sourceUnits.length ? { sourceUnit: { in: scope.sourceUnits } } : {}),
      },
      select: { id: true },
    });
    if (!patient) throw new NotFoundException(`Patient ${patientId} not found in tenant`);

    const result = await engine.recomputeForPatient({
      hostId: scope.hostId,
      tenantId: scope.tenantId,
      clinicId: '', // 集团重算,clinic-级 hint 空字符串
      patientId,
    });
    return { plansCreated: result.plansCreated };
  }
}

// ─────────────────────────────────────────────
// Serializers — DB row → Zod-conformant API shape
// ─────────────────────────────────────────────

type PlanRow = Prisma.FollowupPlanGetPayload<{ include: { reasons: true } }>;
type PatientWithProfile = Prisma.PatientGetPayload<{ include: { profile: true } }>;
type PersonaWithFeatures = Prisma.PersonaGetPayload<{ include: { features: true } }>;
type PlanScriptRow = Prisma.PlanScriptGetPayload<{}>;
type PlanSummaryRow = Prisma.PlanSummaryGetPayload<{}>;
type PlanExecutionRow = Prisma.PlanExecutionGetPayload<{}>;

/// reasons 行 → PlanReasonBrief(给列表用)。signals 透 raw JSON,前端字典翻译富文本。
function toPlanReasonBrief(
  r: PlanRow['reasons'][number],
): PlanReasonBrief {
  return {
    id: r.id,
    scenario: r.scenario,
    subKey: r.subKey,
    // daysSince 用锚点 signalOccurredAt 实时重算(跟详情页/治疗链同源,不随天数陈旧);旧 plan 无锚点 → 回落 baked
    signals: applyLiveDays((r.signals as PlanReasonBrief['signals']) ?? null),
    priorityScore: r.priorityScore,
    reason: r.reason,
    breakdown: r.breakdown ?? null,
  };
}

function serializePlan(p: PlanRow): import('@pac/types').FollowupPlan {
  // FollowupPlanSchema 需要顶层 scenario / inclusionReason / evidence
  // DB 这些在 PlanReason 子表;取 primary reason(MAX priorityScore)填充顶层
  const primary = p.reasons[0];
  const evidence = {
    factIds: Array.from(
      new Set(
        p.reasons.flatMap((r) => ((r.evidence as { factIds?: string[] } | null)?.factIds ?? [])),
      ),
    ),
    personaVersion: undefined,  // 让 caller 在 detail 里通过 persona.version 补全
    ruleIds: p.reasons.map((r) => r.scenario),
  };

  return {
    id: p.id,
    hostId: p.hostId,
    tenantId: p.tenantId,
    patientId: p.patientId,
    personaId: p.personaId,
    targetClinicId: p.targetClinicId,
    scenario: primary?.scenario ?? 'unknown',
    version: p.version,
    priorityScore: p.priorityScore,
    inclusionReason: primary?.reason ?? '(无)',
    recommendedAt: p.recommendedAt?.toISOString() ?? null,
    recommendedRole: p.recommendedRole,
    recommendedChannel: p.recommendedChannel,
    evidence,
    status: p.status as import('@pac/types').PlanStatus,
    recycleAt: p.recycleAt?.toISOString() ?? null,
    snoozedUntil: p.snoozedUntil?.toISOString() ?? null,
    assigneeUserId: p.assigneeUserId,
    assignedAt: p.assignedAt?.toISOString() ?? null,
    createdAt: p.createdAt.toISOString(),
    updatedAt: p.updatedAt.toISOString(),
    supersededAt: p.supersededAt?.toISOString() ?? null,
  };
}

function serializePatient(p: PatientWithProfile): import('@pac/types').Patient {
  // PatientSchema 期望 status enum + 多个 profile 派生字段
  // DB 模型重构:Patient.active boolean → 映射回 status enum
  const status: 'active' | 'archived' = p.active ? 'active' : 'archived';
  return {
    id: p.id,
    hostId: p.hostId,
    tenantId: p.tenantId,
    externalId: p.externalId,
    name: p.name,
    phone: p.phone,
    gender: p.gender,
    birthDate: p.birthDate?.toISOString().slice(0, 10) ?? null,
    preferences: (p.preferences as Record<string, unknown> | null) ?? null,
    doNotContact: p.profile?.doNotContact ?? false,
    doNotContactReason: p.profile?.doNotContactReason ?? null,
    doNotContactAt: null,  // schema 没立柱;后续接入再补
    deceased: p.profile?.deceased ?? false,
    deceasedAt: null,
    status,
    mergedIntoId: null, // v1 不做 merge,字段保留 null
    createdAt: p.createdAt.toISOString(),
    updatedAt: p.updatedAt.toISOString(),
  };
}

function serializePersona(p: PersonaWithFeatures): import('@pac/types').Persona {
  return {
    id: p.id,
    hostId: p.hostId,
    tenantId: p.tenantId,
    patientId: p.patientId,
    version: p.version,
    triggeredBy: p.source,
    computedAt: p.computedAt.toISOString(),
    supersededAt: p.supersededAt?.toISOString() ?? null,
    eventWatermark: p.eventWatermark != null ? p.eventWatermark.toString() : null,
    features: p.features.map((f) => ({
      id: f.id,
      personaId: f.personaId,
      key: f.key,
      description: f.description,
      score: f.score,
      evidence: (f.evidence as Record<string, unknown>) ?? {},
      createdAt: f.createdAt.toISOString(),
    })),
  };
}

function serializeScript(s: PlanScriptRow): import('@pac/types').PlanScript {
  return {
    id: s.id,
    hostId: s.hostId,
    tenantId: s.tenantId,
    planId: s.planId,
    content: s.content,
    status: s.status as import('@pac/types').AssetStatus,
    source: (s.source as import('@pac/types').AssetSource | null) ?? null,
    agentInvocationId: s.agentInvocationId,
    createdAt: s.createdAt.toISOString(),
    updatedAt: s.updatedAt.toISOString(),
  };
}

function serializeSummary(s: PlanSummaryRow): import('@pac/types').PlanSummary {
  return {
    id: s.id,
    hostId: s.hostId,
    tenantId: s.tenantId,
    planId: s.planId,
    type: s.type,
    content: s.content,
    status: s.status as import('@pac/types').AssetStatus,
    source: (s.source as import('@pac/types').AssetSource | null) ?? null,
    agentInvocationId: s.agentInvocationId,
    createdAt: s.createdAt.toISOString(),
    updatedAt: s.updatedAt.toISOString(),
  };
}

function serializeExecution(e: PlanExecutionRow): import('@pac/types').PlanExecution {
  return {
    id: e.id,
    hostId: e.hostId,
    tenantId: e.tenantId,
    executorClinicId: e.executorClinicId,
    planId: e.planId,
    operatorUserId: e.operatorUserId,
    channel: e.channel,
    outcome: e.outcome as import('@pac/types').ExecutionOutcome,
    notes: e.notes,
    abandonReasons: e.abandonReasons,
    scheduledNextAt: e.scheduledNextAt?.toISOString() ?? null,
    createdAt: e.createdAt.toISOString(),
  };
}

function computePlanEvidence(
  plan: PlanRow,
  persona: PersonaWithFeatures | null,
): import('@pac/types').PlanEvidence {
  return {
    factIds: Array.from(
      new Set(
        plan.reasons.flatMap((r) => ((r.evidence as { factIds?: string[] } | null)?.factIds ?? [])),
      ),
    ),
    personaVersion: persona?.version,
    ruleIds: plan.reasons.map((r) => r.scenario),
    agentInvocationIds: [],  // 后续接 PlanScript/Summary 的 agentInvocationId
  };
}
