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(),
  /// 召回反馈已迁到 plan 级(FollowupPlan.recallFeedback),不再随执行
  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(),
  /// 画像标签筛选:"key:value" 逗号串(如 "rfm:important_value,urgency_level:high")。
  /// 维度/取值见 PERSONA_TAG_FILTER_DIMS;同维多选 OR,跨维 AND,匹配当前版画像。
  personaTags: z.string().trim().min(1).optional(),
  /// 只看真实号码(patient.phoneVerified=true,外部对照表核实过的)。query 串传 'true'。
  phoneVerified: z.preprocess(
    (v) => (v === 'true' ? true : v === 'false' ? false : v),
    z.boolean().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(),
  /// 号码真实性(外部对照表核实过 = true);列表给"真"角标 + 筛选用
  phoneVerified: z.boolean().optional(),
  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),
  /// 该 plan 最近一次执行(回访提交)的 outcome — 列表左栏「成功/不成功/保持」角标用。
  /// null = 尚无执行记录。分组/文案/色板查 EXECUTION_OUTCOME_META。
  lastOutcome: ExecutionOutcomeSchema.nullable().optional(),
});
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(),
});
export type SubmitExecutionRequest = z.infer<typeof SubmitExecutionRequestSchema>;

/// 召回反馈(plan 级)— 详情页标题栏拇指 + 文字。data 本质 = 正/反 + 文字。
export const SubmitRecallFeedbackRequestSchema = z.object({
  feedback: z.enum(['up', 'down']),
  /// down 时弹窗收集的文字说明(预选项是快速输入,最终都落这一段文字);up 一般为空
  note: z.string().max(2000).optional(),
});
export type SubmitRecallFeedbackRequest = z.infer<typeof SubmitRecallFeedbackRequestSchema>;

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