import { z } from 'zod';
import {
  AbandonReasonSchema,
  AssetSourceSchema,
  AssetStatusSchema,
  ExecutionChannelSchema,
  ExecutionOutcomeSchema,
  PlanStatusSchema,
} from '../enums';
import { PagingResponseSchema } from './common';
import { PatientSchema } from './patient';
import { PersonaSchema } from './persona';
import { ReasonSignalsSchema } from './reason-signals';

// =============================================================
// Layer 3 — FollowupPlan
// =============================================================

/// 证据引用 — fact 自带 transactionIds 可两跳回溯到原始 transaction(跟 PersonaFeature.evidence 对齐)
export const PlanEvidenceSchema = z
  .object({
    factIds: z.array(z.string().uuid()).optional(),
    personaVersion: z.number().int().optional(),
    agentInvocationIds: z.array(z.string().uuid()).optional(),
    ruleIds: z.array(z.string()).optional(),
  })
  .catchall(z.unknown());
export type PlanEvidence = z.infer<typeof PlanEvidenceSchema>;

export const FollowupPlanSchema = z.object({
  id: z.string().uuid(),
  hostId: z.string().uuid().describe('FK → platforms.id'),
  tenantId: z.string(),
  patientId: z.string().uuid(),
  personaId: z.string().uuid().nullable(),
  /// 期望执行召回的诊所(业务字段,创建锁定);null = 集团统一客服池
  targetClinicId: z.string().nullable(),
  scenario: z.string(),
  version: z.number().int(),
  priorityScore: z.number(),
  inclusionReason: z.string(),
  recommendedAt: z.string().nullable(),
  recommendedRole: z.string().nullable(),
  recommendedChannel: z.string().nullable(),
  evidence: PlanEvidenceSchema,
  status: PlanStatusSchema,
  recycleAt: z.string().nullable(),
  /// 召回冷静期 / 终态抑制窗 deadline(execution 回写按 outcome 计算);
  /// 终态+未到期 → 不重新生成;active+未到期 → 不进召回池(到点浮现)。null=无抑制
  snoozedUntil: z.string().nullable(),
  /// 实际指派给谁(宿主侧 user id);展示用 name 通过 token 字典查
  assigneeUserId: z.string().nullable(),
  assignedAt: z.string().nullable(),
  createdAt: z.string(),
  updatedAt: z.string(),
  /// 被新版本取代的时间;status='active'/'assigned' 等其他状态时为 null
  supersededAt: z.string().nullable(),
});
export type FollowupPlan = z.infer<typeof FollowupPlanSchema>;

// =============================================================
// Layer 3 — PlanScript / PlanSummary(plan 子资产)
// =============================================================

/// PlanScript = 每个 plan 一份完整话术(Markdown 含 ## 开场 / ## 跟进 / ## 异议处理 多子段),
/// 一次 agent 调用产出全部 — schema 不分 type
export const PlanScriptSchema = z.object({
  id: z.string().uuid(),
  hostId: z.string().uuid(),
  tenantId: z.string(),
  planId: z.string().uuid(),
  content: z.string().max(8000).nullable(),
  status: AssetStatusSchema,
  source: AssetSourceSchema.nullable(),
  agentInvocationId: z.string().uuid().nullable(),
  createdAt: z.string(),
  updatedAt: z.string(),
});
export type PlanScript = z.infer<typeof PlanScriptSchema>;

/// PlanSummary = 每个 plan × 3 type(one_page / medical_record / treatment_chain)。
/// 一次 agent 调用产出 3 个 type 内容,共享同一 agentInvocationId
export const PlanSummarySchema = z.object({
  id: z.string().uuid(),
  hostId: z.string().uuid(),
  tenantId: z.string(),
  planId: z.string().uuid(),
  type: z.string(),
  content: z.string().max(8000).nullable(),
  status: AssetStatusSchema,
  source: AssetSourceSchema.nullable(),
  agentInvocationId: z.string().uuid().nullable(),
  createdAt: z.string(),
  updatedAt: z.string(),
});
export type PlanSummary = z.infer<typeof PlanSummarySchema>;

// =============================================================
// Layer 3 — PlanExecution(执行回写)
// =============================================================

export const PlanExecutionSchema = z.object({
  id: z.string().uuid(),
  hostId: z.string().uuid(),
  tenantId: z.string(),
  /// 实际执行客服所在诊所(执行发生地,必填)
  executorClinicId: z.string(),
  planId: z.string().uuid(),
  /// 操作人 user id(从 access token 取);展示 name 走 token 字典 / host /users:resolve
  operatorUserId: z.string(),
  channel: z.string(),
  outcome: ExecutionOutcomeSchema,
  notes: z.string().nullable(),
  abandonReasons: z.array(z.string()),
  abandonOther: z.string().nullable(),
  scheduledNextAt: z.string().nullable(),
  /// 召回反馈(选填·多选)— 对召回算法准确性的反馈,正交于 outcome(见 RECALL_FEEDBACK_OPTIONS)
  recallFeedback: z.array(z.string()),
  createdAt: z.string().describe('提交时间 ≈ 通话结束时间'),
});
export type PlanExecution = z.infer<typeof PlanExecutionSchema>;

// =============================================================
// API 请求 / 响应
// =============================================================

export const ListPlansQuerySchema = z.object({
  scenario: z.string().optional(),
  status: PlanStatusSchema.optional(),
  /// 按 target_clinic_id 过滤召回池(null target 跟着 staff 自己 clinicIds 决定可见性)
  targetClinicId: z.string().optional(),
  /// 按诊所多选过滤(target_clinic_id IN [...])。前端逗号串上线,这里 preprocess 拆数组。
  targetClinicIds: z.preprocess(
    (v) => (typeof v === 'string' ? v.split(',').map((s) => s.trim()).filter(Boolean) : v),
    z.array(z.string()).optional(),
  ),
  assigneeUserId: z.string().optional(),
  view: z.enum(['pool', 'mine', 'all']).optional()
    .describe('"pool" = active+unassigned;  "mine" = assigned to caller;  "all" = no extra filter'),
  /// 关键字搜索:服务端按 patient.name / phone / externalId 模糊匹配(W3 末加,替代前端本页 filter)
  keyword: z.string().trim().min(1).optional(),
  /// 排序:服务端 ORDER BY(W3 末加,替代前端 .sort)
  sort: z.enum(['priority_desc', 'priority_asc', 'created_desc']).default('priority_desc'),
  page: z.coerce.number().int().min(1).default(1),
  pageSize: z.coerce.number().int().min(1).max(100).default(20),
});
export type ListPlansQuery = z.infer<typeof ListPlansQuerySchema>;

/// 列表行用的患者简介 — 避免列表每行再发请求。
/// name 是原值(权限内客服可见),nameMasked 仅作脱敏展示场景备用。
export const PlanPatientBriefSchema = z.object({
  externalId: z.string(),
  name: z.string().nullable(),
  nameMasked: z.string().nullable(),
  phoneMasked: z.string().nullable(),
  gender: z.string().nullable(),
  age: z.number().int().nullable(),
});
export type PlanPatientBrief = z.infer<typeof PlanPatientBriefSchema>;

/// 列表行用的 reason 简介 — 富文本由前端 ReasonLine 用 signals 组装。
/// 跟 plan-aggregate 详情页 reasons 同构(字段子集),保证前端可共享 ReasonLine 组件。
export const PlanReasonBriefSchema = z.object({
  id: z.string().uuid(),
  scenario: z.string(),
  subKey: z.string().nullable(),
  signals: ReasonSignalsSchema.nullable(),
  priorityScore: z.number(),
  /// 老数据 / signals 缺失时的兜底自然语言
  reason: z.string(),
  /// 6 因子算分明细 — 前端 PriorityHover 渲染。无 breakdown 时 fallback 简版文案。
  breakdown: z.unknown().nullable().optional(),
});
export type PlanReasonBrief = z.infer<typeof PlanReasonBriefSchema>;

/// 列表行 = FollowupPlan + patient brief + reasons brief + 中文 scenarioLabel(后端预翻译,前端零计算)
export const PlanListItemSchema = FollowupPlanSchema.extend({
  patient: PlanPatientBriefSchema,
  scenarioLabel: z.string(),
  reasons: z.array(PlanReasonBriefSchema),
});
export type PlanListItem = z.infer<typeof PlanListItemSchema>;

export const ListPlansResponseSchema = z
  .object({ items: z.array(PlanListItemSchema) })
  .extend(PagingResponseSchema.shape);
export type ListPlansResponse = z.infer<typeof ListPlansResponseSchema>;

/// KPI / Tab badge 用的聚合计数 — 后端一次 SQL 给齐,避免列表页 5 个并发 list 请求。
export const PlanCountsResponseSchema = z.object({
  mine: z.number().int(),
  mineAssigned: z.number().int(),
  mineCompleted: z.number().int(),
  pool: z.number().int(),
  all: z.number().int(),
});
export type PlanCountsResponse = z.infer<typeof PlanCountsResponseSchema>;

export const PlanDetailResponseSchema = z.object({
  plan: FollowupPlanSchema,
  patient: PatientSchema,
  persona: PersonaSchema.nullable(),
  script: PlanScriptSchema.nullable().describe('plan-level 单条话术(可能在生成中)'),
  summaries: z.array(PlanSummarySchema).describe('3 种 type 各一条(部分可能在生成中)'),
  executions: z.array(PlanExecutionSchema),
  evidence: PlanEvidenceSchema,
});
export type PlanDetailResponse = z.infer<typeof PlanDetailResponseSchema>;

export const AssignPlanRequestSchema = z.object({
  assigneeUserId: z.string().min(1),
});
export type AssignPlanRequest = z.infer<typeof AssignPlanRequestSchema>;

export const RecyclePlanRequestSchema = z.object({
  reason: z.string().optional(),
});
export type RecyclePlanRequest = z.infer<typeof RecyclePlanRequestSchema>;

export const SubmitExecutionRequestSchema = z.object({
  channel: ExecutionChannelSchema,
  outcome: ExecutionOutcomeSchema,
  notes: z.string().optional(),
  abandonReasons: z.array(AbandonReasonSchema).max(20).optional(),
  abandonOther: z.string().optional(),
  scheduledNextAt: z.string().optional(),
  /// 召回反馈 tag(选填·多选,见 RECALL_FEEDBACK_OPTIONS)
  recallFeedback: z.array(z.string()).max(10).optional(),
});
export type SubmitExecutionRequest = z.infer<typeof SubmitExecutionRequestSchema>;

export const SubmitExecutionResponseSchema = z.object({
  /// plan 新状态(execution outcome 驱动状态机后的结果)
  planStatus: z.string(),
  /// 累计触达次数(本次 ++)
  contactAttempts: z.number().int().min(0),
  /// 是否触发熔断(>= maxContactAttempts → 自动 abandoned)
  breakerTripped: z.boolean(),
  executionId: z.string().uuid(),
});
export type SubmitExecutionResponse = z.infer<typeof SubmitExecutionResponseSchema>;

export const ListExecutionsResponseSchema = z.object({
  items: z.array(PlanExecutionSchema),
});
export type ListExecutionsResponse = z.infer<typeof ListExecutionsResponseSchema>;

export const PlanActionAckSchema = z.object({ ok: z.literal(true) });
export type PlanActionAck = z.infer<typeof PlanActionAckSchema>;

export const RecomputeAckSchema = z.object({
  accepted: z.literal(true),
  plansCreated: z.number().int(),
});
export type RecomputeAck = z.infer<typeof RecomputeAckSchema>;

/// Plan 资产单独 regen API(运维 / 客服不满意场景)
export const RegenerateAssetsRequestSchema = z.object({
  /// true = 先即时 pull 患者数据再 regen
  refreshFacts: z.boolean().default(false),
  /// 指定要重生的资产(空 = 全部:script + 3 个 summary type)
  scripts: z.boolean().optional(),
  summaries: z.array(z.enum(['one_page', 'medical_record', 'treatment_chain'])).optional(),
});
export type RegenerateAssetsRequest = z.infer<typeof RegenerateAssetsRequestSchema>;
