import { ErrorHandler } from '../../utils/error-handler.js';
import { SecurityManager } from '../../utils/security-manager.js';
// Create enhanced error handler with the required methods
class EnhancedErrorHandler extends ErrorHandler {
    async getErrorDetails(errorId) {
        return {
            errorId,
            type: 'validation',
            severity: 'medium',
            message: 'Sample error message',
            timestamp: new Date().toISOString(),
            tool: 'sample_tool',
            context: { userAction: 'Sample action' },
            stackTrace: 'Sample stack trace',
            rootCause: {
                analysis: 'Sample root cause analysis',
                factors: ['Factor 1', 'Factor 2']
            },
            suggestions: [
                {
                    title: 'Sample suggestion',
                    priority: 'high',
                    description: 'Sample description',
                    implementation: 'Sample implementation'
                }
            ],
            relatedErrors: []
        };
    }
    async analyzeErrorPatterns(options) {
        return {
            totalErrors: 5,
            patternsFound: [
                {
                    title: 'Sample pattern',
                    count: 3,
                    frequency: 'Daily',
                    severity: 'medium',
                    description: 'Sample pattern description',
                    affectedTools: ['tool1', 'tool2']
                }
            ],
            recommendations: [
                {
                    title: 'Sample recommendation',
                    priority: 'high',
                    impact: 'High',
                    action: 'Take corrective action'
                }
            ],
            insights: ['Sample insight']
        };
    }
    async getErrorTimeline(options) {
        return [
            {
                timestamp: new Date().toISOString(),
                tool: 'sample_tool',
                type: 'validation',
                severity: 'medium',
                message: 'Sample error',
                context: {
                    userAction: 'Sample action',
                    systemState: 'Normal'
                },
                recovery: 'Automatic recovery'
            }
        ];
    }
    async generateErrorReport(options) {
        const content = options.outputFormat === 'markdown'
            ? '# Error Report\n\nSample error report content'
            : { errors: [], summary: 'Sample summary' };
        return {
            content,
            filePath: options.saveToFile ? '.atlas/reports/error-report.md' : undefined
        };
    }
    async resolveErrorSuggestion(options) {
        return {
            errorId: options.errorId,
            suggestionId: options.suggestionId,
            implementation: options.implementation,
            effectiveness: options.effectiveness,
            notes: options.notes,
            outcome: {
                success: true,
                message: 'Resolution tracked successfully'
            }
        };
    }
    async simulateErrorRecovery(options) {
        return {
            errorType: options.errorType,
            severity: options.severity,
            steps: [
                {
                    name: 'Detection',
                    action: 'Error detected',
                    success: true,
                    simulated: options.dryRun,
                    duration: 100
                },
                {
                    name: 'Recovery',
                    action: 'Recovery initiated',
                    success: true,
                    simulated: options.dryRun,
                    duration: 200
                }
            ],
            results: {
                success: true,
                recoverable: true,
                issues: [],
                recommendations: ['Monitor for recurrence']
            },
            recoveryTime: '300ms',
            effectiveness: '95%'
        };
    }
}
const errorHandler = new EnhancedErrorHandler();
const securityManager = SecurityManager.getInstance();
export async function setupErrorAnalysis(server) {
    return {
        tools: [
            {
                name: 'get_error_details',
                description: 'Get detailed information about a specific error including context, root cause analysis, and recovery suggestions.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        errorId: {
                            type: 'string',
                            description: 'Unique identifier for the error to analyze',
                            minLength: 1
                        },
                        includeContext: {
                            type: 'boolean',
                            default: true,
                            description: 'Include detailed error context and environment information'
                        },
                        includeSuggestions: {
                            type: 'boolean',
                            default: true,
                            description: 'Include recovery suggestions and next steps'
                        }
                    },
                    required: ['errorId'],
                    additionalProperties: false
                }
            },
            {
                name: 'analyze_error_patterns',
                description: 'Analyze error patterns and trends to identify recurring issues and recommend systematic improvements.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        timeRange: {
                            type: 'string',
                            enum: ['1h', '24h', '7d', '30d'],
                            default: '24h',
                            description: 'Time range for error pattern analysis'
                        },
                        errorTypes: {
                            type: 'array',
                            items: {
                                type: 'string',
                                enum: ['validation', 'network', 'permission', 'resource', 'logic', 'external']
                            },
                            description: 'Filter analysis by specific error types'
                        },
                        minOccurrences: {
                            type: 'number',
                            minimum: 1,
                            default: 2,
                            description: 'Minimum occurrences required to identify a pattern'
                        },
                        groupBy: {
                            type: 'string',
                            enum: ['type', 'tool', 'time', 'severity'],
                            default: 'type',
                            description: 'How to group errors for pattern analysis'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'get_error_timeline',
                description: 'Get chronological timeline of errors with context about system state and user actions.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        timeRange: {
                            type: 'string',
                            enum: ['1h', '6h', '24h', '7d'],
                            default: '24h',
                            description: 'Time range for error timeline'
                        },
                        toolName: {
                            type: 'string',
                            description: 'Filter timeline to specific tool (optional)'
                        },
                        severity: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            description: 'Minimum severity level to include'
                        },
                        includeContext: {
                            type: 'boolean',
                            default: true,
                            description: 'Include system context and user actions around each error'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'generate_error_report',
                description: 'Generate comprehensive error analysis report for debugging, monitoring, or team review.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        reportType: {
                            type: 'string',
                            enum: ['summary', 'detailed', 'debugging', 'trends'],
                            default: 'summary',
                            description: 'Type of error report to generate'
                        },
                        timeRange: {
                            type: 'string',
                            enum: ['24h', '7d', '30d'],
                            default: '24h',
                            description: 'Time range for report data'
                        },
                        includeRecommendations: {
                            type: 'boolean',
                            default: true,
                            description: 'Include improvement recommendations'
                        },
                        outputFormat: {
                            type: 'string',
                            enum: ['markdown', 'json', 'csv'],
                            default: 'markdown',
                            description: 'Format for the generated report'
                        },
                        saveToFile: {
                            type: 'boolean',
                            default: false,
                            description: 'Save report to file in .atlas/reports/'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'resolve_error_suggestion',
                description: 'Mark an error resolution suggestion as implemented and track its effectiveness.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        errorId: {
                            type: 'string',
                            description: 'ID of the error that was addressed',
                            minLength: 1
                        },
                        suggestionId: {
                            type: 'string',
                            description: 'ID of the suggestion that was implemented',
                            minLength: 1
                        },
                        implementation: {
                            type: 'string',
                            description: 'Description of how the suggestion was implemented'
                        },
                        effectiveness: {
                            type: 'number',
                            minimum: 1,
                            maximum: 10,
                            description: 'Effectiveness rating (1-10) of the implemented solution'
                        },
                        notes: {
                            type: 'string',
                            description: 'Additional notes about the implementation'
                        }
                    },
                    required: ['errorId', 'suggestionId'],
                    additionalProperties: false
                }
            },
            {
                name: 'simulate_error_recovery',
                description: 'Simulate error recovery procedures to test and validate error handling mechanisms.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        errorType: {
                            type: 'string',
                            enum: ['validation', 'network', 'permission', 'resource', 'logic', 'external'],
                            description: 'Type of error to simulate'
                        },
                        severity: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            default: 'medium',
                            description: 'Severity level for simulation'
                        },
                        context: {
                            type: 'object',
                            description: 'Simulation context and parameters'
                        },
                        dryRun: {
                            type: 'boolean',
                            default: true,
                            description: 'Run simulation without triggering actual errors'
                        }
                    },
                    required: ['errorType'],
                    additionalProperties: false
                }
            }
        ],
        resources: []
    };
}
export async function handleErrorAnalysisTool(name, args) {
    // For now, allow all error analysis access
    // TODO: Implement proper security validation
    try {
        switch (name) {
            case 'get_error_details': {
                const { errorId, includeContext = true, includeSuggestions = true } = args;
                const errorDetails = await errorHandler.getErrorDetails(errorId);
                if (!errorDetails) {
                    throw new Error(`Error with ID '${errorId}' not found`);
                }
                return {
                    content: [{
                            type: 'text',
                            text: formatErrorDetails(errorDetails, includeContext, includeSuggestions)
                        }],
                    structured: {
                        type: 'error_details',
                        errorId,
                        errorDetails,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'analyze_error_patterns': {
                const { timeRange = '24h', errorTypes, minOccurrences = 2, groupBy = 'type' } = args;
                const patterns = await errorHandler.analyzeErrorPatterns({
                    timeRange,
                    errorTypes,
                    minOccurrences,
                    groupBy
                });
                return {
                    content: [{
                            type: 'text',
                            text: formatErrorPatterns(patterns, timeRange, groupBy)
                        }],
                    structured: {
                        type: 'error_patterns',
                        timeRange,
                        groupBy,
                        patterns,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'get_error_timeline': {
                const { timeRange = '24h', toolName, severity, includeContext = true } = args;
                const timeline = await errorHandler.getErrorTimeline({
                    timeRange,
                    toolName,
                    severity,
                    includeContext
                });
                return {
                    content: [{
                            type: 'text',
                            text: formatErrorTimeline(timeline, timeRange, toolName)
                        }],
                    structured: {
                        type: 'error_timeline',
                        timeRange,
                        toolName,
                        severity,
                        timeline,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'generate_error_report': {
                const { reportType = 'summary', timeRange = '24h', includeRecommendations = true, outputFormat = 'markdown', saveToFile = false } = args;
                const report = await errorHandler.generateErrorReport({
                    reportType,
                    timeRange,
                    includeRecommendations,
                    outputFormat,
                    saveToFile
                });
                return {
                    content: [{
                            type: 'text',
                            text: outputFormat === 'markdown' ? report.content :
                                `Error report generated successfully.\n\nFormat: ${outputFormat}\n${saveToFile ? `Saved to: ${report.filePath}` : 'Content available in structured data.'}`
                        }],
                    structured: {
                        type: 'error_report',
                        reportType,
                        timeRange,
                        outputFormat,
                        report,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'resolve_error_suggestion': {
                const { errorId, suggestionId, implementation, effectiveness, notes } = args;
                const resolution = await errorHandler.resolveErrorSuggestion({
                    errorId,
                    suggestionId,
                    implementation,
                    effectiveness,
                    notes,
                    resolvedAt: new Date()
                });
                return {
                    content: [{
                            type: 'text',
                            text: formatResolutionTracking(resolution)
                        }],
                    structured: {
                        type: 'error_resolution_tracked',
                        errorId,
                        suggestionId,
                        resolution,
                        trackedAt: new Date().toISOString()
                    }
                };
            }
            case 'simulate_error_recovery': {
                const { errorType, severity = 'medium', context = {}, dryRun = true } = args;
                // Security check for non-dry-run simulations
                if (!dryRun) {
                    console.warn('Live error simulation requested - this should be used carefully');
                }
                const simulation = await errorHandler.simulateErrorRecovery({
                    errorType,
                    severity,
                    context,
                    dryRun
                });
                return {
                    content: [{
                            type: 'text',
                            text: formatErrorSimulation(simulation, dryRun)
                        }],
                    structured: {
                        type: 'error_recovery_simulation',
                        errorType,
                        severity,
                        dryRun,
                        simulation,
                        simulatedAt: new Date().toISOString()
                    }
                };
            }
            default:
                throw new Error(`Unknown error analysis tool: ${name}`);
        }
    }
    catch (error) {
        console.error(`Error analysis tool error (${name}):`, error);
        throw error;
    }
}
function formatErrorDetails(errorDetails, includeContext, includeSuggestions) {
    const { errorId, type, severity, message, timestamp, tool, context, stackTrace, rootCause, suggestions, relatedErrors } = errorDetails;
    const severityEmoji = severity === 'critical' ? '🔴' : severity === 'high' ? '🟠' : severity === 'medium' ? '🟡' : '🔵';
    let report = `# Error Analysis Report ${severityEmoji}\n\n`;
    report += `## Error Overview\n`;
    report += `- **Error ID**: ${errorId}\n`;
    report += `- **Type**: ${type}\n`;
    report += `- **Severity**: ${severity}\n`;
    report += `- **Tool**: ${tool || 'Unknown'}\n`;
    report += `- **Timestamp**: ${timestamp}\n`;
    report += `- **Message**: ${message}\n\n`;
    if (rootCause) {
        report += `## 🔍 Root Cause Analysis\n`;
        report += `${rootCause.analysis}\n\n`;
        if (rootCause.factors?.length > 0) {
            report += `### Contributing Factors\n`;
            rootCause.factors.forEach((factor, i) => {
                report += `${i + 1}. ${factor}\n`;
            });
            report += '\n';
        }
    }
    if (includeContext && context) {
        report += `## 📋 Error Context\n`;
        if (context.userAction)
            report += `- **User Action**: ${context.userAction}\n`;
        if (context.systemState)
            report += `- **System State**: ${context.systemState}\n`;
        if (context.environment)
            report += `- **Environment**: ${JSON.stringify(context.environment, null, 2)}\n`;
        if (context.parameters)
            report += `- **Parameters**: ${JSON.stringify(context.parameters, null, 2)}\n`;
        report += '\n';
    }
    if (stackTrace) {
        report += `## 🔧 Technical Details\n`;
        report += `\`\`\`\n${stackTrace}\`\`\`\n\n`;
    }
    if (includeSuggestions && suggestions?.length > 0) {
        report += `## 💡 Recovery Suggestions\n`;
        suggestions.forEach((suggestion, i) => {
            report += `### ${i + 1}. ${suggestion.title}\n`;
            report += `**Priority**: ${suggestion.priority}\n`;
            report += `**Description**: ${suggestion.description}\n`;
            if (suggestion.implementation) {
                report += `**Implementation**: ${suggestion.implementation}\n`;
            }
            if (suggestion.riskLevel) {
                report += `**Risk Level**: ${suggestion.riskLevel}\n`;
            }
            report += '\n';
        });
    }
    if (relatedErrors?.length > 0) {
        report += `## 🔗 Related Errors\n`;
        relatedErrors.slice(0, 3).forEach((related, i) => {
            report += `${i + 1}. **${related.type}** - ${related.message} (${related.timestamp})\n`;
        });
        if (relatedErrors.length > 3) {
            report += `... and ${relatedErrors.length - 3} more related errors\n`;
        }
        report += '\n';
    }
    return report;
}
function formatErrorPatterns(patterns, timeRange, groupBy) {
    const { totalErrors, patternsFound, recommendations, insights } = patterns;
    if (totalErrors === 0) {
        return `# Error Pattern Analysis (${timeRange})

✅ **No errors found** in the specified time range.

This indicates:
- System stability is good
- No recurring issues detected
- Error handling mechanisms are working effectively

Continue monitoring for any new patterns that may emerge.`;
    }
    let report = `# Error Pattern Analysis (${timeRange})\n\n`;
    report += `## 📊 Overview\n`;
    report += `- **Total Errors**: ${totalErrors}\n`;
    report += `- **Patterns Found**: ${patternsFound?.length || 0}\n`;
    report += `- **Analysis Method**: Grouped by ${groupBy}\n`;
    report += `- **Time Range**: ${timeRange}\n\n`;
    if (patternsFound?.length > 0) {
        report += `## 🔍 Identified Patterns\n\n`;
        patternsFound.forEach((pattern, i) => {
            const severityEmoji = pattern.severity === 'critical' ? '🔴' : pattern.severity === 'high' ? '🟠' : '🟡';
            report += `### ${i + 1}. ${pattern.title} ${severityEmoji}\n`;
            report += `- **Occurrences**: ${pattern.count}\n`;
            report += `- **Frequency**: ${pattern.frequency}\n`;
            report += `- **Severity**: ${pattern.severity}\n`;
            report += `- **Description**: ${pattern.description}\n`;
            if (pattern.affectedTools?.length > 0) {
                report += `- **Affected Tools**: ${pattern.affectedTools.join(', ')}\n`;
            }
            if (pattern.timePattern) {
                report += `- **Time Pattern**: ${pattern.timePattern}\n`;
            }
            if (pattern.commonContext) {
                report += `- **Common Context**: ${pattern.commonContext}\n`;
            }
            report += '\n';
        });
    }
    if (insights?.length > 0) {
        report += `## 💡 Key Insights\n`;
        insights.forEach((insight, i) => {
            report += `${i + 1}. ${insight}\n`;
        });
        report += '\n';
    }
    if (recommendations?.length > 0) {
        report += `## 🛠️ Recommendations\n`;
        recommendations.forEach((rec, i) => {
            report += `### ${i + 1}. ${rec.title}\n`;
            report += `**Priority**: ${rec.priority}\n`;
            report += `**Impact**: ${rec.impact}\n`;
            report += `**Action**: ${rec.action}\n\n`;
        });
    }
    return report;
}
function formatErrorTimeline(timeline, timeRange, toolName) {
    if (timeline.length === 0) {
        return `# Error Timeline (${timeRange})${toolName ? ` - ${toolName}` : ''}

✅ **No errors found** in the specified time range.

${toolName ? `The ${toolName} tool has been operating without errors.` : 'All tools have been operating without errors.'}`;
    }
    let report = `# Error Timeline (${timeRange})${toolName ? ` - ${toolName}` : ''}\n\n`;
    report += `Found **${timeline.length}** errors in the timeline.\n\n`;
    timeline.forEach((entry, i) => {
        const severityEmoji = entry.severity === 'critical' ? '🔴' : entry.severity === 'high' ? '🟠' : entry.severity === 'medium' ? '🟡' : '🔵';
        report += `## ${i + 1}. ${severityEmoji} ${entry.timestamp}\n`;
        report += `**Tool**: ${entry.tool}\n`;
        report += `**Type**: ${entry.type}\n`;
        report += `**Severity**: ${entry.severity}\n`;
        report += `**Message**: ${entry.message}\n`;
        if (entry.context?.userAction) {
            report += `**User Action**: ${entry.context.userAction}\n`;
        }
        if (entry.context?.systemState) {
            report += `**System State**: ${entry.context.systemState}\n`;
        }
        if (entry.recovery) {
            report += `**Recovery**: ${entry.recovery}\n`;
        }
        report += '\n';
    });
    return report;
}
function formatResolutionTracking(resolution) {
    const { errorId, suggestionId, implementation, effectiveness, notes, outcome } = resolution;
    return `# Error Resolution Tracked ✅

## Resolution Details
- **Error ID**: ${errorId}
- **Suggestion ID**: ${suggestionId}
- **Implementation**: ${implementation || 'Not specified'}
- **Effectiveness**: ${effectiveness ? `${effectiveness}/10` : 'Not rated'}

## Outcome
${outcome?.success ? '✅ **Resolution successful**' : '❌ **Resolution needs refinement**'}

${outcome?.message ? `**Message**: ${outcome.message}` : ''}

${notes ? `## Notes\n${notes}` : ''}

## Impact Tracking
- This resolution will be monitored for continued effectiveness
- Similar errors will be tracked to validate the solution
- Data will be used to improve future error handling

💡 **Thank you for providing feedback** - this helps improve Atlas's error resolution capabilities!`;
}
function formatErrorSimulation(simulation, dryRun) {
    const { errorType, severity, steps, results, recoveryTime, effectiveness } = simulation;
    let report = `# Error Recovery Simulation ${dryRun ? '(Dry Run)' : '(Live Test)'}\n\n`;
    report += `## Simulation Parameters\n`;
    report += `- **Error Type**: ${errorType}\n`;
    report += `- **Severity**: ${severity}\n`;
    report += `- **Mode**: ${dryRun ? 'Validation Only' : 'Live Simulation'}\n`;
    report += `- **Recovery Time**: ${recoveryTime || 'Not measured'}\n\n`;
    if (steps?.length > 0) {
        report += `## Recovery Steps\n`;
        steps.forEach((step, i) => {
            const statusEmoji = step.success ? '✅' : step.simulated ? '🔄' : '❌';
            report += `### ${i + 1}. ${step.name} ${statusEmoji}\n`;
            report += `- **Action**: ${step.action}\n`;
            report += `- **Status**: ${step.success ? 'Success' : step.simulated ? 'Simulated' : 'Failed'}\n`;
            if (step.message)
                report += `- **Message**: ${step.message}\n`;
            if (step.duration)
                report += `- **Duration**: ${step.duration}ms\n`;
            report += '\n';
        });
    }
    if (results) {
        report += `## Simulation Results\n`;
        report += `- **Overall Success**: ${results.success ? 'Yes' : 'No'}\n`;
        report += `- **Recovery Possible**: ${results.recoverable ? 'Yes' : 'No'}\n`;
        report += `- **Effectiveness**: ${effectiveness || 'Not measured'}\n`;
        if (results.issues?.length > 0) {
            report += `\n### Issues Identified\n`;
            results.issues.forEach((issue, i) => {
                report += `${i + 1}. ${issue}\n`;
            });
        }
        if (results.recommendations?.length > 0) {
            report += `\n### Recommendations\n`;
            results.recommendations.forEach((rec, i) => {
                report += `${i + 1}. ${rec}\n`;
            });
        }
    }
    if (dryRun) {
        report += `\n## 🔍 Dry Run Summary\n`;
        report += `- No actual errors were triggered\n`;
        report += `- All recovery mechanisms validated\n`;
        report += `- System state unchanged\n`;
        report += `- Ready for live testing if needed\n`;
    }
    return report;
}
//# sourceMappingURL=index.js.map