import { CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { ConfigManager } from '../../config/config-manager.js';
import { MemoryManager } from './memory-manager.js';
import { DocumentMemory } from './document-memory.js';
import { CodeMemory } from './code-memory.js';
let configManager;
let memoryManager;
let documentMemory;
let codeMemory;
export async function setupMemoryManagementTools(server, config) {
    configManager = config || new ConfigManager();
    memoryManager = new MemoryManager(configManager);
    documentMemory = new DocumentMemory(configManager);
    codeMemory = new CodeMemory(configManager);
    // Initialize memory systems
    await memoryManager.initialize();
    await documentMemory.initialize();
    await codeMemory.initialize();
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
        const { name, arguments: args } = request.params;
        if (!args) {
            throw new Error('No arguments provided');
        }
        switch (name) {
            case 'store_memory': {
                const { content, type, tags = [], metadata = {}, importance = 'medium', } = args;
                try {
                    const memoryId = await memoryManager.store({
                        content,
                        type,
                        tags,
                        metadata,
                        importance,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Memory stored successfully!

🆔 Memory ID: ${memoryId}
📄 Type: ${type}
📊 Importance: ${importance}
🏷️ Tags: ${tags.length > 0 ? tags.join(', ') : 'None'}

💡 This memory is now searchable and will be used to provide better context in future interactions.`,
                            },
                        ],
                        structured: {
                            memoryId,
                            stored: true,
                            type,
                            importance,
                            tags,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to store memory: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'search_memory': {
                const { query, type, tags, limit = 10, includeContext = true, } = args;
                try {
                    const searchQuery = {
                        query,
                        type,
                        tags,
                        limit,
                        includeContext,
                    };
                    const results = await memoryManager.search(searchQuery);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatSearchResults(results, query),
                            },
                        ],
                        structured: {
                            query: searchQuery,
                            results,
                            found: results.length,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Memory search failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'analyze_code_context': {
                const { filePath, functionName, includeRelated = true, depth = 2, } = args;
                try {
                    const context = await codeMemory.analyzeContext({
                        filePath,
                        functionName,
                        includeRelated,
                        depth,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatCodeContext(context),
                            },
                        ],
                        structured: {
                            context,
                            analyzed: true,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Code context analysis failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'update_document_knowledge': {
                const { documentPath, summary, keyPoints = [], relatedFiles = [], } = args;
                try {
                    await documentMemory.updateKnowledge({
                        documentPath,
                        summary,
                        keyPoints: keyPoints || [],
                        relatedFiles: relatedFiles || [],
                        lastUpdated: new Date().toISOString(),
                        topics: keyPoints || [],
                        importance: 'medium',
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Document knowledge updated!

📄 Document: ${documentPath}
📝 Summary: ${summary.substring(0, 100)}${summary.length > 100 ? '...' : ''}
🔑 Key points: ${keyPoints.length}
🔗 Related files: ${relatedFiles.length}

💡 This knowledge will be used to provide better context about project documentation.`,
                            },
                        ],
                        structured: {
                            documentPath,
                            updated: true,
                            keyPointsCount: keyPoints.length,
                            relatedFilesCount: relatedFiles.length,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to update document knowledge: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'get_memory_stats': {
                try {
                    const stats = await memoryManager.getStats();
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatMemoryStats(stats),
                            },
                        ],
                        structured: {
                            stats,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get memory stats: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'clear_memory': {
                const { type, olderThan, confirm = false, } = args;
                if (!confirm) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `⚠️ This will permanently delete memory entries!

${type ? `• Type filter: ${type}` : '• No type filter (all types)'}
${olderThan ? `• Older than: ${olderThan}` : '• No date filter (all dates)'}

To confirm, run: clear_memory confirm=true ${type ? `type="${type}"` : ''} ${olderThan ? `olderThan="${olderThan}"` : ''}`,
                            },
                        ],
                    };
                }
                try {
                    const deletedCount = await memoryManager.clear({ type, olderThan });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Memory cleared!

🗑️ Deleted entries: ${deletedCount}
${type ? `📄 Type: ${type}` : '📄 All types'}
${olderThan ? `📅 Older than: ${olderThan}` : '📅 All dates'}`,
                            },
                        ],
                        structured: {
                            deletedCount,
                            type,
                            olderThan,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to clear memory: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'export_memory': {
                const { format = 'json', includeMetadata = true, outputPath, } = args;
                try {
                    const exportData = await memoryManager.export({
                        format,
                        includeMetadata,
                        outputPath,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `✅ Memory exported successfully!

📄 Format: ${format}
📊 Entries exported: ${exportData.entryCount}
💾 Output: ${exportData.outputPath || 'returned as data'}
📁 Size: ${exportData.size} bytes

${outputPath ? `File saved to: ${exportData.outputPath}` : 'Export data returned in structured response.'}`,
                            },
                        ],
                        structured: {
                            exportData,
                            format,
                            entryCount: exportData.entryCount,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Export failed: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            case 'suggest_related_memories': {
                const { currentContext, type, limit = 5, } = args;
                try {
                    const suggestions = await memoryManager.suggestRelated({
                        currentContext,
                        type,
                        limit,
                    });
                    return {
                        content: [
                            {
                                type: 'text',
                                text: formatRelatedSuggestions(suggestions, currentContext),
                            },
                        ],
                        structured: {
                            suggestions,
                            currentContext,
                            found: suggestions.length,
                        },
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: `❌ Failed to get suggestions: ${error.message}`,
                            },
                        ],
                    };
                }
            }
            default:
                return null;
        }
    });
    return {
        tools: [
            {
                name: 'store_memory',
                description: 'Store information in project memory for future reference',
                inputSchema: {
                    type: 'object',
                    properties: {
                        content: {
                            type: 'string',
                            description: 'The content to store in memory'
                        },
                        type: {
                            type: 'string',
                            enum: ['code', 'documentation', 'decision', 'learning', 'context'],
                            description: 'Type of memory entry'
                        },
                        tags: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Tags for categorizing and searching'
                        },
                        metadata: {
                            type: 'object',
                            description: 'Additional metadata',
                            additionalProperties: true
                        },
                        importance: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            default: 'medium',
                            description: 'Importance level for prioritizing retrieval'
                        },
                    },
                    required: ['content', 'type'],
                },
            },
            {
                name: 'search_memory',
                description: 'Search stored memories using natural language queries',
                inputSchema: {
                    type: 'object',
                    properties: {
                        query: {
                            type: 'string',
                            description: 'Natural language search query'
                        },
                        type: {
                            type: 'string',
                            enum: ['code', 'documentation', 'decision', 'learning', 'context'],
                            description: 'Filter by memory type'
                        },
                        tags: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Filter by tags'
                        },
                        limit: {
                            type: 'number',
                            default: 10,
                            description: 'Maximum number of results'
                        },
                        includeContext: {
                            type: 'boolean',
                            default: true,
                            description: 'Include surrounding context in results'
                        },
                    },
                    required: ['query'],
                },
            },
            {
                name: 'analyze_code_context',
                description: 'Analyze code context and relationships for a specific file or function',
                inputSchema: {
                    type: 'object',
                    properties: {
                        filePath: {
                            type: 'string',
                            description: 'Path to the code file'
                        },
                        functionName: {
                            type: 'string',
                            description: 'Specific function to analyze (optional)'
                        },
                        includeRelated: {
                            type: 'boolean',
                            default: true,
                            description: 'Include related code and dependencies'
                        },
                        depth: {
                            type: 'number',
                            default: 2,
                            description: 'Depth of relationship analysis'
                        },
                    },
                    required: ['filePath'],
                },
            },
            {
                name: 'update_document_knowledge',
                description: 'Update knowledge about project documentation',
                inputSchema: {
                    type: 'object',
                    properties: {
                        documentPath: {
                            type: 'string',
                            description: 'Path to the document'
                        },
                        summary: {
                            type: 'string',
                            description: 'Summary of the document content'
                        },
                        keyPoints: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Key points from the document'
                        },
                        relatedFiles: {
                            type: 'array',
                            items: { type: 'string' },
                            description: 'Related files mentioned in the document'
                        },
                    },
                    required: ['documentPath', 'summary'],
                },
            },
            {
                name: 'get_memory_stats',
                description: 'Get statistics about stored memories',
                inputSchema: {
                    type: 'object',
                    properties: {},
                    required: []
                },
            },
            {
                name: 'clear_memory',
                description: 'Clear stored memories with optional filters',
                inputSchema: {
                    type: 'object',
                    properties: {
                        type: {
                            type: 'string',
                            enum: ['code', 'documentation', 'decision', 'learning', 'context'],
                            description: 'Clear only memories of this type'
                        },
                        olderThan: {
                            type: 'string',
                            description: 'Clear memories older than this date (ISO format)'
                        },
                        confirm: {
                            type: 'boolean',
                            default: false,
                            description: 'Confirm the deletion'
                        },
                    },
                    required: []
                },
            },
            {
                name: 'export_memory',
                description: 'Export stored memories to file or return as data',
                inputSchema: {
                    type: 'object',
                    properties: {
                        format: {
                            type: 'string',
                            enum: ['json', 'markdown', 'csv'],
                            default: 'json',
                            description: 'Export format'
                        },
                        includeMetadata: {
                            type: 'boolean',
                            default: true,
                            description: 'Include metadata in export'
                        },
                        outputPath: {
                            type: 'string',
                            description: 'File path to save export (optional)'
                        },
                    },
                    required: []
                },
            },
            {
                name: 'suggest_related_memories',
                description: 'Get suggestions for related memories based on current context',
                inputSchema: {
                    type: 'object',
                    properties: {
                        currentContext: {
                            type: 'string',
                            description: 'Current context or topic'
                        },
                        type: {
                            type: 'string',
                            enum: ['code', 'documentation', 'decision', 'learning', 'context'],
                            description: 'Filter suggestions by type'
                        },
                        limit: {
                            type: 'number',
                            default: 5,
                            description: 'Maximum number of suggestions'
                        },
                    },
                    required: ['currentContext'],
                },
            },
        ],
        resources: [
            {
                uri: 'memory://project/stats',
                name: 'Project Memory Statistics',
                description: 'Statistics about stored project memories',
                mimeType: 'application/json',
            },
            {
                uri: 'memory://recent/entries',
                name: 'Recent Memory Entries',
                description: 'Recently stored memory entries',
                mimeType: 'application/json',
            },
        ],
    };
}
function formatSearchResults(results, query) {
    if (results.length === 0) {
        return `🔍 No memories found for: "${query}"

💡 Try:
• Using different keywords
• Searching for specific types
• Adding relevant tags
• Storing more context first`;
    }
    return `🔍 Found ${results.length} memories for: "${query}"

${results.map((result, i) => `${i + 1}. **${result.type.toUpperCase()}** (${result.importance}) - Score: ${result.score.toFixed(2)}
   📅 ${new Date(result.timestamp).toLocaleDateString()}
   📝 ${result.content.substring(0, 150)}${result.content.length > 150 ? '...' : ''}
   ${result.tags.length > 0 ? `🏷️ Tags: ${result.tags.join(', ')}` : ''}`).join('\n\n')}

💡 Use the memory ID to get full details or update these memories.`;
}
function formatCodeContext(context) {
    return `🔍 Code Context Analysis

📄 **File**: ${context.filePath}
${context.functionName ? `🔧 **Function**: ${context.functionName}` : ''}

## Summary
${context.summary}

## Dependencies (${context.dependencies.length})
${context.dependencies.map(dep => `• ${dep.name} (${dep.type}): ${dep.description}`).join('\n')}

## Usage Patterns (${context.usagePatterns.length})
${context.usagePatterns.map(pattern => `• ${pattern}`).join('\n')}

${context.relatedCode.length > 0 ? `## Related Code (${context.relatedCode.length})
${context.relatedCode.map(code => `• ${code.file}: ${code.description}`).join('\n')}` : ''}

## Recommendations
${context.recommendations.map(rec => `• ${rec}`).join('\n')}`;
}
function formatMemoryStats(stats) {
    return `📊 Memory Statistics

## Overview
• **Total Entries**: ${stats.totalEntries}
• **Storage Size**: ${(stats.storageSize / 1024).toFixed(2)} KB
• **Last Updated**: ${new Date(stats.lastUpdated).toLocaleString()}

## By Type
${Object.entries(stats.byType).map(([type, count]) => `• ${type}: ${count} entries`).join('\n')}

## By Importance
${Object.entries(stats.byImportance).map(([importance, count]) => `• ${importance}: ${count} entries`).join('\n')}

## Recent Activity
• Entries added today: ${stats.recentActivity.today}
• Entries added this week: ${stats.recentActivity.thisWeek}
• Most active day: ${stats.recentActivity.mostActiveDay}

## Top Tags
${stats.topTags.map(tag => `• ${tag.name}: ${tag.count} uses`).join('\n')}`;
}
function formatRelatedSuggestions(suggestions, context) {
    if (suggestions.length === 0) {
        return `💡 No related memories found for: "${context}"

This might be a new topic - consider storing relevant information for future reference.`;
    }
    return `💡 Related memories for: "${context}"

${suggestions.map((suggestion, i) => `${i + 1}. **${suggestion.type.toUpperCase()}** - Relevance: ${suggestion.score.toFixed(2)}
   📝 ${suggestion.content.substring(0, 100)}${suggestion.content.length > 100 ? '...' : ''}
   🏷️ ${suggestion.tags.join(', ')}`).join('\n\n')}

💡 These memories might provide useful context for your current work.`;
}
//# sourceMappingURL=index.js.map