/**
 * Stream Event Type Definitions
 * 流式事件类型定义 — 扩展现有 StreamChunk 以支持多 Agent 事件
 */

import { SpecialistAgentType, CoordinatorTurnStats, ConsultingStateReport } from './agent.types';

// ============================================================
// Base Stream Event
// ============================================================

/** 所有流式事件的基础类型 */
export interface BaseStreamEvent {
  type: string;
  timestamp?: number;
}

// ============================================================
// Text & Content Events (与现有 StreamChunk 兼容)
// ============================================================

/** 文本内容（流式增量） */
export interface TextStreamEvent extends BaseStreamEvent {
  type: 'text';
  content: string;
  index?: number;
}

/** 工具调用事件 */
export interface ToolUseStreamEvent extends BaseStreamEvent {
  type: 'tool_use';
  toolName: string;
  toolInput: Record<string, unknown>;
  toolUseId: string;
}

/** 工具结果事件 */
export interface ToolResultStreamEvent extends BaseStreamEvent {
  type: 'tool_result';
  toolName: string;
  toolUseId: string;
  result: string;
  isError: boolean;
}

// ============================================================
// Agent Events (新增：多 Agent 协作事件)
// ============================================================

/** Agent 开始工作 */
export interface AgentStartEvent extends BaseStreamEvent {
  type: 'agent_start';
  agentType: SpecialistAgentType;
  agentName: string; // 用户友好名称，如 "政策专家"
  description?: string; // 正在做什么，如 "正在查询TTPS政策..."
}

/** Agent 中间进度 */
export interface AgentProgressEvent extends BaseStreamEvent {
  type: 'agent_progress';
  agentType: SpecialistAgentType;
  message: string; // 进度描述
}

/** Agent 完成工作 */
export interface AgentCompleteEvent extends BaseStreamEvent {
  type: 'agent_complete';
  agentType: SpecialistAgentType;
  agentName: string;
  durationMs: number;
  success: boolean;
}

/** Coordinator 正在思考/编排 */
export interface CoordinatorThinkingEvent extends BaseStreamEvent {
  type: 'coordinator_thinking';
  phase: 'analyzing' | 'orchestrating' | 'synthesizing' | 'evaluating';
  message?: string;
}

// ============================================================
// State & Control Events
// ============================================================

/** 咨询状态更新 */
export interface StateUpdateEvent extends BaseStreamEvent {
  type: 'state_update';
  state: ConsultingStateReport;
}

/** Token 使用情况 */
export interface UsageEvent extends BaseStreamEvent {
  type: 'usage';
  usage: {
    inputTokens: number;
    outputTokens: number;
    cacheCreationTokens?: number;
    cacheReadTokens?: number;
  };
  costUsd: number;
  turnStats?: CoordinatorTurnStats;
}

/** 流结束事件 */
export interface EndStreamEvent extends BaseStreamEvent {
  type: 'end';
  totalTokens: {
    inputTokens: number;
    outputTokens: number;
  };
  totalCostUsd: number;
  turnCount: number;
  agentsUsed: SpecialistAgentType[];
}

/** 评估门控警告事件 */
export interface EvaluationWarningEvent extends BaseStreamEvent {
  type: 'evaluation_warning';
  results: Array<{
    ruleId: string;
    ruleName: string;
    ruleType: string;
    passed: boolean;
    failureAction: string;
    message?: string;
  }>;
  action: string;
}

/** 错误事件 */
export interface ErrorStreamEvent extends BaseStreamEvent {
  type: 'error';
  code: 'MAX_TURNS_REACHED' | 'BUDGET_EXCEEDED' | 'USER_ABORTED' | 'API_ERROR' | 'RATE_LIMIT' | 'OVERLOADED' | 'INTERNAL_ERROR';
  message: string;
  recoverable: boolean;
}

// ============================================================
// Union Type
// ============================================================

/** 所有可能的流式事件 */
export type StreamEvent =
  | TextStreamEvent
  | ToolUseStreamEvent
  | ToolResultStreamEvent
  | AgentStartEvent
  | AgentProgressEvent
  | AgentCompleteEvent
  | CoordinatorThinkingEvent
  | StateUpdateEvent
  | UsageEvent
  | EndStreamEvent
  | EvaluationWarningEvent
  | ErrorStreamEvent;

// ============================================================
// Agent Friendly Names (用于前端展示)
// ============================================================

export const AGENT_DISPLAY_NAMES: Record<SpecialistAgentType, string> = {
  [SpecialistAgentType.POLICY_EXPERT]: '政策专家',
  [SpecialistAgentType.ASSESSMENT_EXPERT]: '评估专家',
  [SpecialistAgentType.STRATEGIST]: '策略顾问',
  [SpecialistAgentType.OBJECTION_HANDLER]: '异议处理专家',
  [SpecialistAgentType.CASE_ANALYST]: '案例分析师',
  [SpecialistAgentType.MEMORY_MANAGER]: '记忆管理',
};

export const AGENT_DESCRIPTIONS: Record<SpecialistAgentType, string> = {
  [SpecialistAgentType.POLICY_EXPERT]: '正在查询移民政策信息...',
  [SpecialistAgentType.ASSESSMENT_EXPERT]: '正在评估您的移民资格...',
  [SpecialistAgentType.STRATEGIST]: '正在分析最佳咨询策略...',
  [SpecialistAgentType.OBJECTION_HANDLER]: '正在准备专业解答...',
  [SpecialistAgentType.CASE_ANALYST]: '正在查找类似成功案例...',
  [SpecialistAgentType.MEMORY_MANAGER]: '正在整理您的信息...',
};

// ============================================================
// WebSocket Event Names (前端监听)
// ============================================================

export const WS_EVENTS = {
  // 现有事件（保持兼容）
  CONNECTED: 'connected',
  MESSAGE: 'message',
  STREAM_START: 'stream_start',
  STREAM_CHUNK: 'stream_chunk',
  STREAM_END: 'stream_end',
  TOOL_CALL: 'tool_call',
  TOOL_RESULT: 'tool_result',
  ERROR: 'error',

  // 新增事件（多 Agent）
  AGENT_START: 'agent_start',
  AGENT_PROGRESS: 'agent_progress',
  AGENT_COMPLETE: 'agent_complete',
  COORDINATOR_THINKING: 'coordinator_thinking',
  STATE_UPDATE: 'state_update',
} as const;
