/**
 * Multi-Agent System Type Definitions
 * 多 Agent 系统类型定义
 */

// ============================================================
// Agent Identity & Configuration
// ============================================================

/** 专家 Agent 类型枚举 */
export enum SpecialistAgentType {
  POLICY_EXPERT = 'policy_expert',
  ASSESSMENT_EXPERT = 'assessment_expert',
  STRATEGIST = 'strategist',
  OBJECTION_HANDLER = 'objection_handler',
  CASE_ANALYST = 'case_analyst',
  MEMORY_MANAGER = 'memory_manager',
}

/** Agent 模型选择 */
export type AgentModel = 'claude-sonnet-4-5-20250929' | 'claude-sonnet-4-20250514' | 'claude-haiku-4-5-20251001';

/** Agent 配置 */
export interface AgentConfig {
  type: SpecialistAgentType;
  model: AgentModel;
  maxTurns: number;         // 内部工具循环最大轮次
  maxTokens: number;        // 单次 API 调用最大 token
  temperature?: number;     // API 温度参数 (0-1)，undefined 使用模型默认值
  timeoutMs: number;        // 执行超时
  isConcurrencySafe: boolean; // 是否可以与其他 Agent 并行
}

/** 所有 Agent 的默认配置 */
export const AGENT_CONFIGS: Record<SpecialistAgentType, AgentConfig> = {
  [SpecialistAgentType.POLICY_EXPERT]: {
    type: SpecialistAgentType.POLICY_EXPERT,
    model: 'claude-sonnet-4-20250514',
    maxTurns: 3,
    maxTokens: 2048,
    temperature: 0,         // 政策信息需要确定性
    timeoutMs: 30000,
    isConcurrencySafe: true,
  },
  [SpecialistAgentType.ASSESSMENT_EXPERT]: {
    type: SpecialistAgentType.ASSESSMENT_EXPERT,
    model: 'claude-sonnet-4-20250514',
    maxTurns: 3,
    maxTokens: 3000,
    temperature: 0,         // 评估需要确定性
    timeoutMs: 45000,
    isConcurrencySafe: true,
  },
  [SpecialistAgentType.STRATEGIST]: {
    type: SpecialistAgentType.STRATEGIST,
    model: 'claude-sonnet-4-20250514',
    maxTurns: 2,
    maxTokens: 1500,
    temperature: 0.3,       // 策略建议需要一定创造性
    timeoutMs: 20000,
    isConcurrencySafe: true,
  },
  [SpecialistAgentType.OBJECTION_HANDLER]: {
    type: SpecialistAgentType.OBJECTION_HANDLER,
    model: 'claude-sonnet-4-20250514',
    maxTurns: 3,
    maxTokens: 2048,
    temperature: 0.2,       // 异议处理需要共情+少量变化
    timeoutMs: 30000,
    isConcurrencySafe: true,
  },
  [SpecialistAgentType.CASE_ANALYST]: {
    type: SpecialistAgentType.CASE_ANALYST,
    model: 'claude-haiku-4-5-20251001',
    maxTurns: 2,
    maxTokens: 1500,
    temperature: 0,         // 案例检索需要确定性
    timeoutMs: 15000,
    isConcurrencySafe: true,
  },
  [SpecialistAgentType.MEMORY_MANAGER]: {
    type: SpecialistAgentType.MEMORY_MANAGER,
    model: 'claude-haiku-4-5-20251001',
    maxTurns: 2,
    maxTokens: 1024,
    temperature: 0,         // 信息提取需要确定性
    timeoutMs: 15000,
    isConcurrencySafe: false, // 有写操作（save_user_memory）
  },
};

// ============================================================
// Agent Invocation (Coordinator → Specialist)
// ============================================================

/** Policy Expert 输入 */
export interface PolicyExpertInput {
  query: string;
  category?: string; // QMAS | GEP | IANG | TTPS | CIES | TECHTAS
  includeProcessSteps?: boolean;
  includeRequirements?: boolean;
}

/** Policy Expert 输出 */
export interface PolicyExpertOutput {
  policySummary: string;
  requirements?: string[];
  processSteps?: string[];
  importantNotes?: string[];
  sources?: string[];
}

/** Assessment Expert 输入 */
export interface AssessmentExpertInput {
  userInfo: Record<string, unknown>;
  targetCategories?: string[];
  conversationContext?: string; // 最近几轮对话摘要
}

/** 单个类别的评估结果 */
export interface CategoryAssessment {
  category: string;
  categoryName: string;
  eligible: boolean;
  score: number;          // 0-100
  confidence: number;     // 0-1
  highlights: string[];
  concerns: string[];
  missingInfo?: string[];
  subClass?: string;      // e.g. TTPS A/B/C
}

/** Assessment Expert 输出 */
export interface AssessmentExpertOutput {
  assessments: CategoryAssessment[];
  overallRecommendation: string;
  topRecommended: string[];   // 最推荐的类别
  suitabilityScore: number;   // 综合评分 0-100
  summary: string;
}

/** Strategist 输入 */
export interface StrategistInput {
  conversationSummary: string;
  currentStage?: string;           // 当前咨询阶段
  latestUserMessage?: string;      // 最新用户消息
  currentTurnCount: number;
  collectedInfo: Record<string, unknown>;
  userSentiment?: string;
  hasAssessment: boolean;
  hasConverted: boolean;
}

/** Strategist 输出 */
export interface StrategistOutput {
  currentStage: string;
  recommendedNextAction: string;
  missingInfoPriorities: string[];
  conversionSignals: string[];
  toneAdjustment?: string;
  suggestedQuestions?: string[];
  urgencyLevel: 'low' | 'medium' | 'high';
}

/** Objection Handler 输入 */
export interface ObjectionHandlerInput {
  objection: string;
  category?: string;              // 相关移民类别
  userContext: string;
  previousObjections?: string[];
}

/** Objection Handler 输出 */
export interface ObjectionHandlerOutput {
  objectionCategory: string;
  empathyResponse: string;
  factualRebuttal: string;
  successStoryReference?: string;
  suggestedResponse: string;
  followUpQuestion: string;
}

/** Case Analyst 输入 */
export interface CaseAnalystInput {
  userProfile: Record<string, unknown>;
  targetCategory: string;
  focusArea?: string;
}

/** Case Analyst 输出 */
export interface CaseAnalystOutput {
  matchedCases: Array<{
    summary: string;
    similarityFactors: string[];
    outcome: string;
    timeline: string;
  }>;
  keyTakeaways: string[];
}

/** Memory Manager Action Types */
export type MemoryAction = 'load_context' | 'save_info' | 'extract_from_conversation' | 'summarize_profile';

/** Memory Manager 输入 */
export interface MemoryManagerInput {
  action: MemoryAction;
  userId: string;
  /** For save_info: key-value pairs to save */
  dataToSave?: Record<string, unknown>;
  /** For extract_from_conversation: recent messages */
  recentMessages?: string;
  /** For load_context: optional query for relevance filtering */
  contextQuery?: string;
}

/** Memory Manager 输出 */
export interface MemoryManagerOutput {
  action: MemoryAction;
  /** For load_context */
  userMemories?: Array<{
    type: string;
    content: string;
    importance: number;
  }>;
  /** For save_info / extract */
  savedFields?: string[];
  /** For summarize_profile */
  profileSummary?: string;
  collectedInfo?: Record<string, unknown>;
}

// ============================================================
// Agent Execution Tracking
// ============================================================

/** Agent 执行记录 */
export interface AgentExecutionRecord {
  agentType: SpecialistAgentType;
  startedAt: Date;
  completedAt?: Date;
  durationMs?: number;
  inputTokens: number;
  outputTokens: number;
  toolCallsCount: number;
  success: boolean;
  error?: string;
}

/** Coordinator 单轮执行统计 */
export interface CoordinatorTurnStats {
  turnNumber: number;
  agentsInvoked: AgentExecutionRecord[];
  directToolCalls: number;
  coordinatorInputTokens: number;
  coordinatorOutputTokens: number;
  totalCostUsd: number;
}

// ============================================================
// Coordinator Loop Parameters
// ============================================================

/** Agent Loop 参数 */
export interface AgentLoopParams {
  messages: ClaudeMessage[];
  systemPrompt: SystemPromptBlock[];
  tools: ToolDefinition[];
  maxTurns: number;
  maxBudgetUsd: number;
  conversationId: string;
  userId: string;
  abortSignal?: AbortSignal;
  /** 已经消耗的轮次（递归时累加）*/
  currentTurnCount?: number;
  /** 已经消耗的成本（递归时累加）*/
  currentCostUsd?: number;
  /** 可选评估门控回调。提供时，在 yield 'end' 前调用检查回复质量。 */
  evaluationGate?: (
    responseText: string,
    turnCount: number,
    agentsUsed: string[],
  ) => Promise<import('../coordinator/evaluation-gate.service').GateResult>;
  /** Structured Output — 传入 Claude API 的 output_config */
  outputConfig?: { format: Record<string, unknown> };
}

/** Claude API 消息格式 */
export interface ClaudeMessage {
  role: 'user' | 'assistant';
  content: string | ContentBlock[];
}

/** System Prompt Block (支持 cache_control) */
export interface SystemPromptBlock {
  type: 'text';
  text: string;
  cache_control?: { type: 'ephemeral' };
}

/** Content Block 类型 */
export type ContentBlock =
  | { type: 'text'; text: string }
  | { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }
  | { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean }
  | { type: 'image'; source: { type: 'base64'; media_type: string; data: string } };

/** Tool Definition for Claude API */
export interface ToolDefinition {
  name: string;
  description: string;
  input_schema: Record<string, unknown>;
  /** 是否可以与其他工具并发执行 */
  isConcurrencySafe?: boolean;
}

// ============================================================
// Consulting State (LLM 自报告，非程序控制)
// ============================================================

/** 咨询状态（由 Coordinator 在回复中自行报告） */
export interface ConsultingStateReport {
  currentStage: string;
  collectedInfo: Record<string, unknown>;
  assessmentDone: boolean;
  assessmentResult?: {
    topRecommended: string[];
    suitabilityScore: number;
  };
  nextAction: string;
  conversionReady: boolean;
}
