/**
 * Copyright (c) 2025 TWork Team. All rights reserved.
 * This source code is licensed under the TWork License.
 */

/**
 * 记忆管道宿主无关接口（WP2-T2.2）
 *
 * 移植自 TencentDB-Agent-Memory MemoryCore/src/core/types.ts，按 TWork 裁剪：
 * - 保留：Logger / RuntimeContext / LLMRunParams / LLMRunner / LLMRunnerFactory /
 *   HostAdapter / CompletedTurn / CaptureResult / RecallResult / 检索参数
 * - 去除：Langfuse 上报（traceName/tags/buildTraceParams）、tool 循环
 *   （enableTools/tools/storage——一期 L1 提取/去重均为纯文本 miniModel）、
 *   COS 存储（Phase 6 再议）
 *
 * 设计原则（同上游）：
 * 1. 记忆管道只依赖本文件的接口，绝不依赖具体宿主
 * 2. TWork 作为宿主提供 HostAdapter 实现（LLMRunner 适配 runMiniCompletion /
 *    AgentBackend.complete()，见设计稿 §6.1）
 * 3. MemoryRuntimeContext 是会话/用户身份的唯一事实源
 */

// ============================
// Logger
// ============================

/** 记忆管道统一日志接口（同上游 Logger；debug 可选） */
export interface MemoryLogger {
  debug?: (message: string) => void;
  info: (message: string) => void;
  warn: (message: string) => void;
  error: (message: string) => void;
}

// ============================
// RuntimeContext（隔离维度映射见设计稿 §6.2）
// ============================

/**
 * 记忆管道运行时上下文。
 *
 * 上游三维隔离（user_id/team_id/agent_id）在 TWork 的映射：
 * - 用户级记忆：userId='user'，teamId='default'
 * - 工作区级记忆：teamId=workspace_id
 * - agentId 固定 'default'（TWork 无多 agent 租户）
 */
export interface MemoryRuntimeContext {
  /** 用户标识（TWork 单用户客户端固定 'user'） */
  userId: string;
  /** 会话 id（= twork conversationId） */
  sessionId: string;
  /** 会话 key（跨回合稳定，L0/L1 分组用；TWork 用 conversationId） */
  sessionKey: string;
  /** 工作区 id（团队维度隔离；用户级记忆为 'default'） */
  workspaceId: string;
  /** 工作区目录（工作区级记忆锚定的 fs 根） */
  workspaceDir: string;
}

// ============================
// LLMRunner
// ============================

/** 单次 LLM 执行参数（上游裁剪版：无 tool 循环 / 无 Langfuse / 无 COS） */
export interface LLMRunParams {
  /** 用户消息（若提供 systemPrompt 则作为 user 消息，否则为合并 prompt） */
  prompt: string;
  /** 可选 system prompt（提取/去重 prompt 均为 system+user 双段） */
  systemPrompt?: string;
  /** 任务标识（日志与诊断用，如 'memory.l1-extract' / 'memory.l1-dedup'） */
  taskId: string;
  /** 超时毫秒（缺省 120_000；去重场景调用方传 30_000） */
  timeoutMs?: number;
  /** 最大输出 token（可选） */
  maxTokens?: number;
  /** 外部中止信号（与内部超时叠加生效） */
  abortSignal?: AbortSignal;
}

/**
 * 统一 LLM 执行接口（同上游 LLMRunner.run 契约）：
 * - 返回 LLM 文本输出；无输出时返回空串
 * - 超时/网络错误/不可恢复失败抛异常（调用方负责 fallback，如 l1-dedup 的 fallback store）
 */
export interface LLMRunner {
  run(params: LLMRunParams): Promise<string>;
}

/** 创建 LLMRunner 的选项（上游裁剪版：无 modelRef 覆盖，miniModel 由宿主定） */
export interface LLMRunnerCreateOptions {
  /** 透传超时默认值（可选） */
  defaultTimeoutMs?: number;
}

/** 宿主提供的 LLMRunner 工厂（同上游 LLMRunnerFactory） */
export interface LLMRunnerFactory {
  createRunner(opts?: LLMRunnerCreateOptions): LLMRunner;
}

// ============================
// HostAdapter
// ============================

/**
 * 宿主适配器（同上游 HostAdapter）——把 TWork 的环境/事件/能力翻译为
 * 记忆管道的统一接口。回答三个问题：
 * - 当前会话/用户是谁 → getRuntimeContext()
 * - 怎么调 LLM       → getLLMRunnerFactory()
 * - 日志往哪写        → getLogger()
 */
export interface MemoryHostAdapter {
  /** 宿主类型标识（TWork 固定 'twork'；保留字段供条件行为，应极少用） */
  readonly hostType: 'twork';
  /** 当前会话的运行时上下文（每回合可不同——会话切换时刷新） */
  getRuntimeContext(): MemoryRuntimeContext;
  /** 宿主提供的日志实例 */
  getLogger(): MemoryLogger;
  /** 宿主配置的 LLMRunner 工厂（miniModel） */
  getLLMRunnerFactory(): LLMRunnerFactory;
}

// ============================
// CompletedTurn / 结果类型
// ============================

/** 一个已完成的对话回合（L0 录入输入，同上游 CompletedTurn 裁剪版） */
export interface CompletedTurn {
  /** 用户原始消息文本（注入召回上下文前的干净文本） */
  userText: string;
  /** 助手回复文本 */
  assistantText: string;
  /** 本回合全部消息（可含工具调用/结果） */
  messages: Array<{ role: string; content: string; timestamp?: number }>;
  /** 会话 key */
  sessionKey: string;
  /** 会话 id（可选，子会话分组用） */
  sessionId?: string;
  /** 回合开始时刻（epoch ms） */
  startedAt?: number;
}

/** 录入（capture）结果（同上游 CaptureResult，无向量字段——vec 默认关） */
export interface CaptureResult {
  /** L0 录入的消息条数 */
  l0RecordedCount: number;
  /** 是否已通知管道调度器（L1/L2/L3 触发评估） */
  schedulerNotified: boolean;
  /** 实际捕获的消息（过滤后） */
  filteredMessages: Array<{ role: string; content: string; timestamp: number }>;
}

/** 召回结果（同上游 RecallResult；错误类型 Phase 3 引入 RecallErrors 后细化为结构体） */
export interface RecallResult {
  /** L1 相关记忆——拼入 user 消息前缀（动态，每轮） */
  prependContext?: string;
  /** 稳定召回上下文——进 system 稳定段（persona / scene 导航 / 工具指南，可缓存） */
  appendSystemContext?: string;
  /** 命中的 L1 记忆（含分数，指标用） */
  recalledL1Memories?: Array<{ content: string; score: number; type: string }>;
  /** L3 Persona 内容（Phase 5 后填充） */
  recalledL3Persona?: string | null;
  /** 实际使用的检索策略（keyword / embedding / hybrid） */
  recallStrategy?: string;
  /** 结构化失败信号（成功时 undefined；超时/存储错误等填充） */
  error?: { code: number; message: string };
  /** 部分成功标记：部分步骤成功、部分失败时为 true */
  partial?: boolean;
}

/** L1 记忆检索参数（memory_search 工具入参） */
export interface MemorySearchParams {
  query: string;
  limit?: number;
  type?: string;
  /** 隔离过滤：'user' | workspace_id；缺省按 RuntimeContext */
  isolation?: string;
}

/** L0 对话检索参数（conversation_search 工具入参） */
export interface ConversationSearchParams {
  query: string;
  limit?: number;
  sessionKey?: string;
}
