import { z } from 'zod';

// =============================================================
// Layer 2 — Persona / PersonaFeature(API 出读形态)
// =============================================================

/// 证据引用 — Persona 重算/Plan 引擎可两跳回溯到原始 transaction:
///   factIds → patient_facts → transaction_ids → patient_transactions
export const PersonaEvidenceSchema = z
  .object({
    factIds: z.array(z.string().uuid()).optional(),
    agentInvocationIds: z.array(z.string().uuid()).optional(),
    ruleIds: z.array(z.string()).optional(),
    promptVersion: z.string().optional(),
  })
  .catchall(z.unknown());
export type PersonaEvidence = z.infer<typeof PersonaEvidenceSchema>;

export const PersonaFeatureSchema = z.object({
  id: z.string().uuid(),
  personaId: z.string().uuid(),
  /// 特征键(如 value / treatment_chain_status / recall_risk;见 enums:PersonaFeatureKey 候选)
  key: z.string(),
  /// 自然语言描述,自包含。**不要拆字段**(架构约束,PDF §6.4)
  description: z.string(),
  /// 可选数值评分,用于排序/筛选;不承载语义
  score: z.number().nullable().optional(),
  evidence: PersonaEvidenceSchema,
  createdAt: z.string(),
});
export type PersonaFeature = z.infer<typeof PersonaFeatureSchema>;

export const PersonaSchema = z.object({
  id: z.string().uuid(),
  hostId: z.string().uuid().describe('FK → platforms.id'),
  tenantId: z.string(),
  patientId: z.string().uuid(),
  version: z.number().int(),
  /// 触发来源:txn:<id> / manual:<userId> / scheduled:<cronId>
  triggeredBy: z.string(),
  computedAt: z.string(),
  /// null = 当前版本
  supersededAt: z.string().nullable(),
  /// 本次重算时已响应到的 transaction.event_seq(BigInt 转字符串以避免 JSON 精度问题)
  eventWatermark: z.string().nullable(),
  features: z.array(PersonaFeatureSchema),
});
export type Persona = z.infer<typeof PersonaSchema>;

export const PersonaResponseSchema = z.object({
  persona: PersonaSchema.nullable(),
});
export type PersonaResponse = z.infer<typeof PersonaResponseSchema>;
