import {
  Injectable,
  Logger,
  NotFoundException,
  BadRequestException,
  ForbiddenException,
} from '@nestjs/common';
import type { Prisma } from '@prisma/client';
import {
  Permission,
  planScenarioLabel,
  applyLiveDays,
  type ListPlansResponse,
  type PlanCountsResponse,
  type PlanDetailResponse,
  type PlanReasonBrief,
} from '@pac/types';
import { maskName, maskPhone } from '@pac/utils';
import { PrismaService } from '../../prisma/prisma.service';
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 { ExecutionService } from './execution.service';

/**
 * 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 配置)

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

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

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

  async list(
    scope: TenantScopeContext,
    query: ListPlansQueryDto,
    permissions: readonly string[],
  ): Promise<ListPlansResponse> {
    const where: Prisma.FollowupPlanWhereInput = {
      hostId: scope.hostId,
      tenantId: scope.tenantId,
      supersededAt: null,
    };

    // 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 隔离(staff 只能看自己 clinic 的 target,或 null 集团池;leader 看全 tenant)
    if (view !== 'all' && scope.clinicIds.length > 0) {
      where.OR = [
        { targetClinicId: { in: scope.clinicIds } },
        { targetClinicId: null },
      ];
    }

    // W3 末:服务端 keyword 模糊匹配 — patient.name / phone / externalId 任一命中
    // (替代前端本页 .filter,改成跨全表搜索,真实接入万人级数据后才能用)
    const patientWhere: Prisma.PatientWhereInput = {};
    if (query.keyword) {
      patientWhere.OR = [
        { name: { contains: query.keyword, mode: 'insensitive' } },
        { phone: { contains: query.keyword } },
        { 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;
    }

    // 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]));

    return {
      items: rows.map((p) => {
        const base = serializePlan(p);
        const patient = patientById.get(p.patientId);
        return {
          ...base,
          scenarioLabel: planScenarioLabel(base.scenario),
          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,
    };
  }

  // ─────────────────────────────────────────────
  // 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): Promise<PlanDetailResponse> {
    const plan = await this.prisma.followupPlan.findUnique({
      where: { id: planId },
      include: { reasons: { orderBy: { priorityScore: 'desc' } } },
    });
    if (!plan || plan.hostId !== scope.hostId || plan.tenantId !== scope.tenantId) {
      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),
      patient: serializePatient(patient),
      persona: persona ? serializePersona(persona) : null,
      script: scriptRow ? serializeScript(scriptRow) : null,
      summaries: summariesRows.map(serializeSummary),
      executions: executions.map(serializeExecution),
      evidence: computePlanEvidence(plan, persona),
    };
  }

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

  async assign(
    scope: TenantScopeContext,
    planId: string,
    assigneeUserId: string,
    _assigneeRole?: string,
  ): Promise<void> {
    const plan = await this.prisma.followupPlan.findUnique({
      where: { id: planId },
      select: { id: true, hostId: true, tenantId: true, status: true, assigneeUserId: 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();
    await this.prisma.followupPlan.update({
      where: { id: planId },
      data: {
        status: 'assigned',
        assigneeUserId,
        assignedAt: now,
        recycleAt: new Date(now.getTime() + RECYCLE_TIMEOUT_HOURS * 3600 * 1000),
      },
    });
  }

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

  async recycle(scope: TenantScopeContext, planId: string): Promise<void> {
    const plan = await this.prisma.followupPlan.findUnique({
      where: { id: planId },
      select: { id: true, hostId: true, tenantId: true, status: true },
    });
    if (!plan || plan.hostId !== scope.hostId || plan.tenantId !== scope.tenantId) {
      throw new NotFoundException(`Plan ${planId} not found`);
    }
    if (plan.status !== 'assigned') {
      throw new BadRequestException(`Plan 当前状态 ${plan.status},不能 recycle(只 assigned 可回收)`);
    }
    await this.prisma.followupPlan.update({
      where: { id: planId },
      data: {
        status: 'active',
        assigneeUserId: null,
        assignedAt: null,
        recycleAt: null,
      },
    });
  }

  // ─────────────────────────────────────────────
  // 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 },
      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,
    abandonOther: e.abandonOther,
    scheduledNextAt: e.scheduledNextAt?.toISOString() ?? null,
    createdAt: e.createdAt.toISOString(),
  };
}

function calcAge(birthDate: Date): number {
  const now = new Date();
  let age = now.getFullYear() - birthDate.getFullYear();
  const m = now.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && now.getDate() < birthDate.getDate())) age--;
  return age;
}

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
  };
}
