/**
 * Context Injection Type Definitions
 * 动态上下文注入系统类型定义
 */

// ============================================================
// Context Types (每种注入上下文的类型)
// ============================================================

/** 上下文类型枚举 */
export enum ContextType {
  USER_MEMORY = 'user_memory',
  COLLECTED_INFO = 'collected_info',
  CONVERSATION_STATS = 'conversation_stats',
  ASSESSMENT_RESULT = 'assessment_result',
  RELEVANT_KNOWLEDGE = 'relevant_knowledge',
  SIMILAR_EXPERIENCES = 'similar_experiences',
  DEVICE_CONTEXT = 'device_context',
  AGENT_HISTORY = 'agent_history',
}

/** 上下文注入优先级（越小越优先，token 不足时从低优先级开始丢弃） */
export const CONTEXT_PRIORITY: Record<ContextType, number> = {
  [ContextType.COLLECTED_INFO]: 1,        // 最重要：已收集的用户信息
  [ContextType.ASSESSMENT_RESULT]: 2,     // 已有的评估结果
  [ContextType.USER_MEMORY]: 3,           // 用户历史记忆
  [ContextType.CONVERSATION_STATS]: 4,    // 对话统计
  [ContextType.RELEVANT_KNOWLEDGE]: 5,    // 相关知识
  [ContextType.AGENT_HISTORY]: 6,         // 最近 Agent 调用记录
  [ContextType.SIMILAR_EXPERIENCES]: 7,   // 系统经验
  [ContextType.DEVICE_CONTEXT]: 8,        // 设备信息（可丢弃）
};

/** 上下文缓存策略 */
export const CONTEXT_CACHE_TTL: Record<ContextType, number> = {
  [ContextType.USER_MEMORY]: 60000,           // 1 min — 可能被其他 Agent 更新
  [ContextType.COLLECTED_INFO]: 0,            // 不缓存 — 每轮都从对话状态读取
  [ContextType.CONVERSATION_STATS]: 0,        // 不缓存 — 实时计算
  [ContextType.ASSESSMENT_RESULT]: 300000,    // 5 min — 评估结果稳定
  [ContextType.RELEVANT_KNOWLEDGE]: 30000,    // 30 sec — 可能话题变化
  [ContextType.SIMILAR_EXPERIENCES]: 300000,  // 5 min — 系统经验稳定
  [ContextType.DEVICE_CONTEXT]: Infinity,     // 整个对话不变
  [ContextType.AGENT_HISTORY]: 0,             // 不缓存 — 每轮更新
};

// ============================================================
// Context Data Interfaces
// ============================================================

/** 用户记忆上下文 */
export interface UserMemoryContext {
  type: ContextType.USER_MEMORY;
  memories: Array<{
    memoryType: string;
    content: string;
    importance: number;
    createdAt: string;
  }>;
  profileSummary?: string;
}

/** 已收集信息上下文 */
export interface CollectedInfoContext {
  type: ContextType.COLLECTED_INFO;
  info: Record<string, unknown>;
  completionRate: number; // 0-1, 信息收集完成度
  missingFields: string[];
}

/** 对话统计上下文 */
export interface ConversationStatsContext {
  type: ContextType.CONVERSATION_STATS;
  totalTurns: number;
  userMessageCount: number;
  assistantMessageCount: number;
  durationMinutes: number;
  agentsInvokedThisSession: string[];
  lastAgentUsed?: string;
}

/** 评估结果上下文 */
export interface AssessmentResultContext {
  type: ContextType.ASSESSMENT_RESULT;
  topRecommended: string[];
  suitabilityScore: number;
  summary: string;
  completedAt: string;
}

/** 相关知识上下文 */
export interface RelevantKnowledgeContext {
  type: ContextType.RELEVANT_KNOWLEDGE;
  articles: Array<{
    title: string;
    summary: string;
    category: string;
    similarity: number;
  }>;
}

/** 系统经验上下文 */
export interface SimilarExperiencesContext {
  type: ContextType.SIMILAR_EXPERIENCES;
  experiences: Array<{
    experienceType: string;
    content: string;
    confidence: number;
  }>;
}

/** 设备上下文 */
export interface DeviceContextData {
  type: ContextType.DEVICE_CONTEXT;
  ip?: string;
  region?: string;
  timezone?: string;
  userAgent?: string;
  deviceType?: 'mobile' | 'desktop' | 'tablet';
  isNewUser: boolean;
  firstMessageTime: string;
}

/** Agent 调用历史上下文 */
export interface AgentHistoryContext {
  type: ContextType.AGENT_HISTORY;
  recentCalls: Array<{
    agentType: string;
    input: string;   // 简短摘要
    output: string;  // 简短摘要
    durationMs: number;
    timestamp: string;
  }>;
}

/** 上下文数据联合类型 */
export type ContextData =
  | UserMemoryContext
  | CollectedInfoContext
  | ConversationStatsContext
  | AssessmentResultContext
  | RelevantKnowledgeContext
  | SimilarExperiencesContext
  | DeviceContextData
  | AgentHistoryContext;

// ============================================================
// Context Injection Result
// ============================================================

/** 单个上下文注入块 */
export interface ContextInjectionBlock {
  contextType: ContextType;
  priority: number;
  content: string;           // 格式化后的文本
  estimatedTokens: number;   // 估算 token 数
  fromCache: boolean;
}

/** 上下文注入结果 */
export interface ContextInjectionResult {
  blocks: ContextInjectionBlock[];
  totalEstimatedTokens: number;
  droppedContexts: ContextType[];  // 因 token 限制被丢弃的上下文
  injectionText: string;           // 拼接后的注入文本
}

// ============================================================
// Context Injector Configuration
// ============================================================

/** 上下文注入器配置 */
export interface ContextInjectorConfig {
  /** 上下文注入的最大 token 预算（预留给上下文的 token 数）*/
  maxContextTokens: number;    // default: 4000

  /** 是否启用自动压缩 */
  enableAutoCompaction: boolean;  // default: true

  /** 触发压缩的 token 阈值（总消息 token 数）*/
  compactionThreshold: number;   // default: 80000 (80k tokens)

  /** 压缩后的目标 token 数 */
  compactionTarget: number;      // default: 40000 (40k tokens)

  /** 启用的上下文类型 */
  enabledContextTypes: ContextType[];
}

/** 默认配置 */
export const DEFAULT_CONTEXT_CONFIG: ContextInjectorConfig = {
  maxContextTokens: 4000,
  enableAutoCompaction: true,
  compactionThreshold: 80000,
  compactionTarget: 40000,
  enabledContextTypes: Object.values(ContextType),
};

// ============================================================
// Conversation Context (传入 Coordinator 的完整上下文)
// ============================================================

/** 对话上下文（从 ConversationService 传入） */
export interface ConversationContext {
  conversationId: string;
  userId: string;
  messages: Array<{
    role: 'user' | 'assistant' | 'system';
    content: string;
    metadata?: Record<string, unknown>;
    createdAt: Date;
  }>;
  consultingState?: {
    currentStage?: string;
    collectedInfo?: Record<string, unknown>;
    assessmentResult?: Record<string, unknown>;
    stageHistory?: Array<{
      stageId: string;
      enteredAt: string;
      turnsInStage: number;
    }>;
  };
  deviceInfo?: {
    ip?: string;
    userAgent?: string;
    fingerprint?: string;
    region?: string;
  };
  agentHistory?: Array<{
    agentType: string;
    input: string;
    output: string;
    durationMs: number;
    timestamp: string;
  }>;
  isNewConversation: boolean;
}
