import { Type } from '@sinclair/typebox';
import { AnyAgentTool } from '../common.js';
import { MemoryProvider } from '../../memory/provider.js';
import { Repository } from 'typeorm';
import { NetaClawMemoryTypeEntity } from '../../entity/memory_type.js';

const BUILTIN_TYPES = [
  { key: 'user', name: '用户画像', description: '用户偏好、角色、习惯' },
  { key: 'project', name: '项目知识', description: '项目进展、决策、约束' },
  { key: 'feedback', name: '行为反馈', description: '用户对 Agent 行为的纠正或确认' },
  { key: 'reference', name: '引用资源', description: '外部资源链接、文档地址' },
];

export function createMemoryListTypesTool(
  memoryTypeRepo?: Repository<NetaClawMemoryTypeEntity>,
): AnyAgentTool {
  return {
    name: 'memory_list_types',
    label: '查看记忆类型',
    description: '列出所有可用的记忆类型，帮助选择正确的类型存储记忆。',
    parameters: Type.Object({}),
    async execute(): Promise<string> {
      let types = BUILTIN_TYPES;
      if (memoryTypeRepo) {
        try {
          const dbTypes = await memoryTypeRepo.find();
          if (dbTypes.length > 0) {
            types = dbTypes.map(t => ({ key: t.key, name: t.name, description: t.description }));
          }
        } catch { /* fallback to builtin */ }
      }
      return types.map(t => `- ${t.key}: ${t.name} — ${t.description}`).join('\n');
    },
  };
}

export function createMemoryStatsTool(
  provider: MemoryProvider,
  agentName: string,
  userId: string,
): AnyAgentTool {
  return {
    name: 'memory_stats',
    label: '记忆统计',
    description: '查看已存储的记忆数量和类型分布，帮助决定是更新已有记忆还是创建新的。',
    parameters: Type.Object({}),
    async execute(): Promise<string> {
      const entries = await provider.list({ agentName, userId, limit: 1000 });
      const byType: Record<string, number> = {};
      for (const e of entries) {
        byType[e.type] = (byType[e.type] || 0) + 1;
      }
      const lines = Object.entries(byType).map(([t, c]) => `  ${t}: ${c} 条`);
      return `记忆总数: ${entries.length}\n类型分布:\n${lines.join('\n')}`;
    },
  };
}

import { registerSchema } from '../catalog.js';
registerSchema({
  name: 'memory_list_types',
  toolset: 'memory',
  description: '列出所有可用的记忆类型。',
  capability: 'text',
  visibility: 'tool',
});
registerSchema({
  name: 'memory_stats',
  toolset: 'memory',
  description: '查看记忆数量和类型分布。',
  capability: 'text',
  visibility: 'tool',
});
