/**
 * Memory Manager Specialist Agent
 * 记忆管理 Agent — 提取、存储和检索用户信息
 *
 * 使用 Haiku 模型（主要是提取和存储，结构化任务）
 * isConcurrencySafe = false（有写操作）
 */

import { Injectable } from '@nestjs/common';
import Anthropic from '@anthropic-ai/sdk';
import { BaseSpecialistService } from './base-specialist.service';
import {
  AGENT_CONFIGS,
  SpecialistAgentType,
  ToolDefinition,
  MemoryManagerInput,
} from '../types/agent.types';
import { KnowledgeClientService } from '../../knowledge/knowledge-client.service';
import { buildMemoryManagerPrompt } from '../prompts/memory-manager-prompt';

@Injectable()
export class MemoryManagerService extends BaseSpecialistService {
  constructor(
    anthropicClient: Anthropic,
    private readonly knowledgeClient: KnowledgeClientService,
  ) {
    super(AGENT_CONFIGS[SpecialistAgentType.MEMORY_MANAGER], anthropicClient);
  }

  protected getSystemPrompt(): string {
    return buildMemoryManagerPrompt();
  }

  protected getTools(): ToolDefinition[] {
    return [
      {
        name: 'get_user_context',
        description: '获取用户的历史记忆信息',
        input_schema: {
          type: 'object',
          properties: {
            query: { type: 'string', description: '检索查询' },
          },
          required: ['query'],
        },
      },
      {
        name: 'save_user_memory',
        description: '保存用户信息到长期记忆',
        input_schema: {
          type: 'object',
          properties: {
            userId: { type: 'string', description: '用户 ID' },
            memoryType: {
              type: 'string',
              enum: ['FACT', 'PREFERENCE', 'INTENT'],
              description: '记忆类型: FACT(个人信息/事实), PREFERENCE(偏好), INTENT(意向)',
            },
            content: { type: 'string', description: '要保存的内容' },
            importance: {
              type: 'number',
              description: '重要程度 1-10',
            },
          },
          required: ['userId', 'memoryType', 'content'],
        },
      },
    ];
  }

  protected async executeTool(
    toolName: string,
    toolInput: Record<string, unknown>,
  ): Promise<string> {
    switch (toolName) {
      case 'get_user_context': {
        try {
          return await this.knowledgeClient.getUserContext(
            toolInput.query as string,
          ) || '无用户历史记录。';
        } catch (error) {
          return '用户记忆检索暂时不可用。';
        }
      }
      case 'save_user_memory': {
        try {
          await this.knowledgeClient.saveUserMemory({
            userId: toolInput.userId as string,
            memoryType: (toolInput.memoryType as 'FACT' | 'PREFERENCE' | 'INTENT') || 'FACT',
            content: toolInput.content as string,
            importance: (toolInput.importance as number) || 5,
          });
          return `已成功保存 ${toolInput.memoryType} 类型的记忆。`;
        } catch (error) {
          return '记忆保存失败，请稍后重试。';
        }
      }
      default:
        return `Unknown tool: ${toolName}`;
    }
  }

  /**
   * Typed execute method
   */
  async manageMemory(input: MemoryManagerInput): Promise<string> {
    const userMessage = this.buildUserMessage(input);
    const { result } = await this.execute(userMessage);
    return result;
  }

  private buildUserMessage(input: MemoryManagerInput): string {
    switch (input.action) {
      case 'load_context':
        return [
          `请加载用户 ${input.userId} 的上下文信息。`,
          input.contextQuery ? `重点检索：${input.contextQuery}` : '',
          '请返回 JSON 格式的用户记忆列表。',
        ].filter(Boolean).join('\n');

      case 'save_info':
        const dataStr = input.dataToSave
          ? Object.entries(input.dataToSave)
              .map(([k, v]) => `  - ${k}: ${v}`)
              .join('\n')
          : '  (无数据)';
        return [
          `请为用户 ${input.userId} 保存以下信息：`,
          dataStr,
          '请依次保存每条信息，并返回保存结果。',
        ].join('\n');

      case 'extract_from_conversation':
        return [
          `请从以下对话中提取用户 ${input.userId} 的关键信息并保存：`,
          '',
          input.recentMessages || '(无对话内容)',
          '',
          '请提取并保存：个人信息、偏好、意向、评估相关数据等。',
          '返回 JSON 格式，列出提取并保存的字段。',
        ].join('\n');

      case 'summarize_profile':
        return [
          `请为用户 ${input.userId} 生成完整的画像摘要。`,
          '请先加载所有可用的用户记忆，然后整合为结构化的用户画像。',
          '返回 JSON 格式，包含 profileSummary 和 collectedInfo。',
        ].join('\n');

      default:
        return `执行记忆操作：${input.action}（用户：${input.userId}）`;
    }
  }
}
