/**
 * 记忆工具（2 个）
 *
 * memory_store, memory_search
 *
 * @see docs/MetonaAI-Desktop 架构与交互设计.html — 9 个基础工具
 */

import type { IMetonaTool, ToolExecutionContext } from '../../types/metona-tool';
import type { MetonaToolDef } from '../../../harness/types';
import { MetonaToolCategory, MetonaRiskLevel } from '../../../harness/types';
import type { MemoryManager } from '../../memory/manager';

// ===== 7. memory_store =====

export class MemoryStoreTool implements IMetonaTool {
  readonly definition: MetonaToolDef = {
    name: 'memory_store',
    description: 'Store a piece of information in persistent memory. Useful for remembering important facts, decisions, or user preferences across sessions.',
    parameters: {
      type: 'object',
      properties: {
        content: { type: 'string', description: 'The memory content to store' },
        type: { type: 'string', description: 'Memory type: "episodic" (events), "semantic" (knowledge), or "working" (task state)', enum: ['episodic', 'semantic', 'working'] },
        importance: { type: 'number', description: 'Importance score 0-1 (default 0.5)' },
        source: { type: 'string', description: 'Source of the memory', enum: ['user_input', 'tool_result', 'agent_thought', 'imported'] },
      },
      required: ['content', 'type'],
    },
    category: MetonaToolCategory.DATABASE,
    riskLevel: MetonaRiskLevel.MEDIUM,
    requiresPermission: false,
    timeoutMs: 10_000,
  };

  constructor(private memoryManager: MemoryManager) {}

  async execute(args: Record<string, unknown>, context: ToolExecutionContext): Promise<unknown> {
    const content = args.content as string;
    const type = args.type as 'episodic' | 'semantic' | 'working';
    const importance = (args.importance as number) ?? 0.5;
    const source = (args.source as 'user_input' | 'tool_result' | 'agent_thought' | 'imported') ?? 'agent_thought';

    // v0.3.0 修复: store() 是同步方法，移除多余的 await 避免误导维护者
    const id = this.memoryManager.store({
      type,
      content,
      source,
      importance,
      sessionId: context.sessionId,
    });

    return { id, type, content_preview: content.slice(0, 100), importance };
  }
}

// ===== 8. memory_search =====

export class MemorySearchTool implements IMetonaTool {
  readonly definition: MetonaToolDef = {
    name: 'memory_search',
    description: 'Search persistent memory for relevant information. Returns memories sorted by relevance.',
    parameters: {
      type: 'object',
      properties: {
        query: { type: 'string', description: 'Search query or keywords' },
        type: { type: 'string', description: 'Filter by memory type', enum: ['episodic', 'semantic', 'working'] },
        topK: { type: 'number', description: 'Number of results (default 5)' },
        threshold: { type: 'number', description: 'Minimum importance score 0-1 (default 0.7). Filters memories by importance, not search relevance.' },
      },
      required: ['query'],
    },
    category: MetonaToolCategory.DATABASE,
    riskLevel: MetonaRiskLevel.SAFE,
    requiresPermission: false,
    timeoutMs: 10_000,
  };

  constructor(private memoryManager: MemoryManager) {}

  async execute(args: Record<string, unknown>, _context: ToolExecutionContext): Promise<unknown> {
    const query = args.query as string;
    const type = args.type as 'episodic' | 'semantic' | 'working' | undefined;
    const topK = (args.topK as number) ?? 5;
    const threshold = (args.threshold as number) ?? 0.7;

    // v0.3.0 修复: search() 是同步方法，移除多余的 await 避免误导维护者
    const results = this.memoryManager.search(query, {
      topK,
      type,
      minImportance: threshold,
    });

    return {
      query,
      results: results.map((r) => ({
        id: r.id,
        type: r.type,
        content: r.content.slice(0, 500),
        importance: r.importance,
        score: r.score,
      })),
      count: results.length,
    };
  }
}
