import { PerformanceMonitor } from '../../utils/performance-monitor.js';
import { SecurityManager } from '../../utils/security-manager.js';
const performanceMonitor = PerformanceMonitor.getInstance();
const securityManager = SecurityManager.getInstance();
export async function setupPerformanceMonitoring(server) {
    return {
        tools: [
            {
                name: 'get_system_metrics',
                description: 'Get comprehensive system performance metrics including success rates, response times, and error statistics. Use this to monitor overall Atlas health and identify performance bottlenecks.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        timeRange: {
                            type: 'string',
                            enum: ['1h', '24h', '7d', '30d'],
                            default: '24h',
                            description: 'Time range for metrics aggregation'
                        },
                        includeDetails: {
                            type: 'boolean',
                            default: false,
                            description: 'Include detailed breakdown by tool and operation'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'get_tool_metrics',
                description: 'Get detailed performance metrics for a specific tool including execution times, success rates, and quality scores. Use this to analyze individual tool performance.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        toolName: {
                            type: 'string',
                            description: 'Name of the tool to analyze',
                            minLength: 1
                        },
                        timeRange: {
                            type: 'string',
                            enum: ['1h', '24h', '7d', '30d'],
                            default: '24h',
                            description: 'Time range for metrics aggregation'
                        },
                        includeQuality: {
                            type: 'boolean',
                            default: true,
                            description: 'Include quality evaluation metrics'
                        }
                    },
                    required: ['toolName'],
                    additionalProperties: false
                }
            },
            {
                name: 'generate_performance_alerts',
                description: 'Generate alerts for performance issues including slow tools, high error rates, and quality degradation. Use this proactively to identify problems.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        alertTypes: {
                            type: 'array',
                            items: {
                                type: 'string',
                                enum: ['performance', 'errors', 'quality', 'costs', 'security']
                            },
                            default: ['performance', 'errors', 'quality'],
                            description: 'Types of alerts to generate'
                        },
                        severity: {
                            type: 'string',
                            enum: ['low', 'medium', 'high', 'critical'],
                            default: 'medium',
                            description: 'Minimum severity level for alerts'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'export_performance_metrics',
                description: 'Export performance metrics to CSV or JSON format for external analysis. Use this to create reports or integrate with other monitoring systems.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        format: {
                            type: 'string',
                            enum: ['csv', 'json'],
                            default: 'csv',
                            description: 'Export format'
                        },
                        timeRange: {
                            type: 'string',
                            enum: ['1h', '24h', '7d', '30d'],
                            default: '24h',
                            description: 'Time range for data export'
                        },
                        includeQuality: {
                            type: 'boolean',
                            default: true,
                            description: 'Include quality evaluation data'
                        },
                        filePath: {
                            type: 'string',
                            description: 'Optional file path to save export (defaults to .atlas/exports/)'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            },
            {
                name: 'record_quality_evaluation',
                description: 'Record quality evaluation feedback for a tool execution. Use this to rate outputs and improve recommendation accuracy.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        toolName: {
                            type: 'string',
                            description: 'Name of the tool being evaluated',
                            minLength: 1
                        },
                        quality: {
                            type: 'number',
                            minimum: 1,
                            maximum: 10,
                            description: 'Quality rating from 1 (poor) to 10 (excellent)'
                        },
                        feedback: {
                            type: 'string',
                            description: 'Optional detailed feedback about the output quality'
                        },
                        executionId: {
                            type: 'string',
                            description: 'Optional execution ID to link evaluation to specific run'
                        }
                    },
                    required: ['toolName', 'quality'],
                    additionalProperties: false
                }
            },
            {
                name: 'get_quality_metrics',
                description: 'Get quality evaluation metrics for tools including average ratings, feedback trends, and improvement recommendations.',
                inputSchema: {
                    type: 'object',
                    properties: {
                        toolName: {
                            type: 'string',
                            description: 'Specific tool to analyze (optional - defaults to all tools)'
                        },
                        timeRange: {
                            type: 'string',
                            enum: ['1h', '24h', '7d', '30d'],
                            default: '7d',
                            description: 'Time range for quality analysis'
                        },
                        minRatings: {
                            type: 'number',
                            minimum: 1,
                            default: 3,
                            description: 'Minimum number of ratings required for analysis'
                        }
                    },
                    required: [],
                    additionalProperties: false
                }
            }
        ],
        resources: []
    };
}
export async function handlePerformanceMonitoringTool(name, args) {
    // For now, allow all performance monitoring access
    // TODO: Implement proper security validation when SecurityManager has the required methods
    try {
        switch (name) {
            case 'get_system_metrics': {
                const { timeRange = '24h', includeDetails = false } = args;
                const metrics = performanceMonitor.getSystemMetrics();
                return {
                    content: [{
                            type: 'text',
                            text: formatSystemMetrics(metrics, includeDetails, timeRange)
                        }],
                    structured: {
                        type: 'system_metrics',
                        timeRange,
                        metrics,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'get_tool_metrics': {
                const { toolName, timeRange = '24h', includeQuality = true } = args;
                const metrics = performanceMonitor.getToolMetrics(toolName);
                const qualityMetrics = includeQuality ?
                    performanceMonitor.getQualityMetrics(toolName) : null;
                return {
                    content: [{
                            type: 'text',
                            text: formatToolMetrics(toolName, metrics, qualityMetrics, timeRange)
                        }],
                    structured: {
                        type: 'tool_metrics',
                        toolName,
                        timeRange,
                        metrics,
                        qualityMetrics,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'generate_performance_alerts': {
                const { alertTypes = ['performance', 'errors', 'quality'], severity = 'medium' } = args;
                const alerts = performanceMonitor.generateAlerts();
                const filteredAlerts = alerts.filter(alert => alertTypes.includes(alert.type) &&
                    getSeverityLevel(alert.severity) >= getSeverityLevel(severity));
                return {
                    content: [{
                            type: 'text',
                            text: formatAlerts(filteredAlerts)
                        }],
                    structured: {
                        type: 'performance_alerts',
                        alertCount: filteredAlerts.length,
                        alerts: filteredAlerts,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'export_performance_metrics': {
                const { format = 'csv', timeRange = '24h', includeQuality = true, filePath } = args;
                const exportData = performanceMonitor.exportMetrics(format);
                const exportPath = filePath || `.atlas/exports/performance-metrics-${new Date().toISOString().split('T')[0]}.${format}`;
                // Save to file (simplified version)
                const fs = await import('fs/promises');
                const path = await import('path');
                await fs.mkdir(path.dirname(exportPath), { recursive: true });
                await fs.writeFile(exportPath, exportData);
                return {
                    content: [{
                            type: 'text',
                            text: `Performance metrics exported successfully to: ${exportPath}\n\nFormat: ${format.toUpperCase()}\nTime Range: ${timeRange}\nQuality Data: ${includeQuality ? 'Included' : 'Excluded'}`
                        }],
                    structured: {
                        type: 'export_result',
                        exportPath,
                        format,
                        timeRange,
                        includeQuality,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            case 'record_quality_evaluation': {
                const { toolName, quality, feedback, executionId } = args;
                performanceMonitor.recordQualityEvaluation({
                    toolName,
                    outputQuality: quality,
                    appropriatenessScore: quality, // Use quality as proxy
                    completenessScore: quality,
                    accuracyScore: quality,
                    comments: feedback || '',
                    evaluationCriteria: ['user_feedback']
                });
                return {
                    content: [{
                            type: 'text',
                            text: `Quality evaluation recorded successfully:\n\nTool: ${toolName}\nRating: ${quality}/10\n${feedback ? `Feedback: ${feedback}` : ''}`
                        }],
                    structured: {
                        type: 'quality_evaluation_recorded',
                        toolName,
                        quality,
                        feedback,
                        executionId,
                        recordedAt: new Date().toISOString()
                    }
                };
            }
            case 'get_quality_metrics': {
                const { toolName, timeRange = '7d', minRatings = 3 } = args;
                const qualityMetrics = performanceMonitor.getQualityMetrics(toolName);
                return {
                    content: [{
                            type: 'text',
                            text: formatQualityMetrics(qualityMetrics, timeRange, minRatings)
                        }],
                    structured: {
                        type: 'quality_metrics',
                        toolName,
                        timeRange,
                        minRatings,
                        metrics: qualityMetrics,
                        generatedAt: new Date().toISOString()
                    }
                };
            }
            default:
                throw new Error(`Unknown performance monitoring tool: ${name}`);
        }
    }
    catch (error) {
        console.error(`Performance monitoring tool error (${name}):`, error);
        throw error;
    }
}
function formatSystemMetrics(metrics, includeDetails, timeRange) {
    const { totalExecutions, successRate, averageResponseTime, errorCount, topTools } = metrics;
    let report = `# System Performance Report (${timeRange})\n\n`;
    report += `## Overall Health\n`;
    report += `- **Total Executions**: ${totalExecutions}\n`;
    report += `- **Success Rate**: ${(successRate * 100).toFixed(1)}%\n`;
    report += `- **Average Response Time**: ${averageResponseTime}ms\n`;
    report += `- **Total Errors**: ${errorCount}\n\n`;
    if (topTools?.length > 0) {
        report += `## Most Used Tools\n`;
        topTools.slice(0, 5).forEach((tool, index) => {
            report += `${index + 1}. **${tool.name}** - ${tool.executions} executions\n`;
        });
        report += '\n';
    }
    if (includeDetails && metrics.toolBreakdown) {
        report += `## Detailed Tool Performance\n`;
        Object.entries(metrics.toolBreakdown).forEach(([toolName, toolMetrics]) => {
            report += `### ${toolName}\n`;
            report += `- Executions: ${toolMetrics.executions}\n`;
            report += `- Success Rate: ${(toolMetrics.successRate * 100).toFixed(1)}%\n`;
            report += `- Avg Response Time: ${toolMetrics.averageResponseTime}ms\n\n`;
        });
    }
    return report;
}
function formatToolMetrics(toolName, metrics, qualityMetrics, timeRange) {
    let report = `# Tool Performance Report: ${toolName} (${timeRange})\n\n`;
    if (metrics) {
        report += `## Performance Metrics\n`;
        report += `- **Executions**: ${metrics.executions || 0}\n`;
        report += `- **Success Rate**: ${((metrics.successRate || 0) * 100).toFixed(1)}%\n`;
        report += `- **Average Response Time**: ${metrics.averageResponseTime || 'N/A'}ms\n`;
        report += `- **Error Count**: ${metrics.errorCount || 0}\n\n`;
    }
    else {
        report += `## Performance Metrics\n`;
        report += `No performance data available for ${toolName} in the specified time range.\n\n`;
    }
    if (qualityMetrics && qualityMetrics.evaluationCount > 0) {
        report += `## Quality Metrics\n`;
        report += `- **Average Quality**: ${qualityMetrics.averageQuality.toFixed(1)}/10\n`;
        report += `- **Total Evaluations**: ${qualityMetrics.evaluationCount}\n`;
        report += `- **Quality Trend**: ${qualityMetrics.trend || 'Stable'}\n\n`;
        if (qualityMetrics.recentFeedback?.length > 0) {
            report += `## Recent Feedback\n`;
            qualityMetrics.recentFeedback.slice(0, 3).forEach((feedback, index) => {
                report += `${index + 1}. Rating: ${feedback.quality}/10 - ${feedback.feedback || 'No comment'}\n`;
            });
            report += '\n';
        }
    }
    else {
        report += `## Quality Metrics\n`;
        report += `No quality evaluations available for ${toolName}.\n\n`;
    }
    return report;
}
function formatQualityMetrics(qualityMetrics, timeRange, minRatings) {
    let report = `# Quality Metrics Report (${timeRange})\n\n`;
    if (!qualityMetrics || Object.keys(qualityMetrics).length === 0) {
        report += `No quality data available for the specified criteria.\n`;
        report += `Minimum ratings required: ${minRatings}\n`;
        return report;
    }
    report += `## Overall Quality Summary\n`;
    const tools = Object.entries(qualityMetrics);
    const totalEvaluations = tools.reduce((sum, [_, metrics]) => sum + (metrics.evaluationCount || 0), 0);
    const avgQuality = tools.reduce((sum, [_, metrics]) => sum + (metrics.averageQuality || 0), 0) / tools.length;
    report += `- **Tools Evaluated**: ${tools.length}\n`;
    report += `- **Total Evaluations**: ${totalEvaluations}\n`;
    report += `- **Average Quality**: ${avgQuality.toFixed(1)}/10\n\n`;
    report += `## Tool Quality Breakdown\n`;
    tools
        .filter(([_, metrics]) => (metrics.evaluationCount || 0) >= minRatings)
        .sort(([_, a], [__, b]) => (b.averageQuality || 0) - (a.averageQuality || 0))
        .forEach(([toolName, metrics]) => {
        report += `### ${toolName}\n`;
        report += `- **Average Quality**: ${metrics.averageQuality.toFixed(1)}/10\n`;
        report += `- **Evaluations**: ${metrics.evaluationCount}\n`;
        report += `- **Trend**: ${metrics.trend || 'Stable'}\n\n`;
    });
    return report;
}
function formatAlerts(alerts) {
    if (alerts.length === 0) {
        return "# Performance Alerts\n\n✅ No performance issues detected. All systems operating normally.";
    }
    let report = `# Performance Alerts (${alerts.length} issues detected)\n\n`;
    const criticalAlerts = alerts.filter(a => a.severity === 'critical');
    const highAlerts = alerts.filter(a => a.severity === 'high');
    const mediumAlerts = alerts.filter(a => a.severity === 'medium');
    const lowAlerts = alerts.filter(a => a.severity === 'low');
    if (criticalAlerts.length > 0) {
        report += `## 🚨 Critical Alerts\n`;
        criticalAlerts.forEach(alert => {
            report += `- **${alert.title}**: ${alert.message}\n`;
            if (alert.suggestion)
                report += `  💡 *${alert.suggestion}*\n`;
        });
        report += '\n';
    }
    if (highAlerts.length > 0) {
        report += `## ⚠️ High Priority Alerts\n`;
        highAlerts.forEach(alert => {
            report += `- **${alert.title}**: ${alert.message}\n`;
            if (alert.suggestion)
                report += `  💡 *${alert.suggestion}*\n`;
        });
        report += '\n';
    }
    if (mediumAlerts.length > 0) {
        report += `## ⚡ Medium Priority Alerts\n`;
        mediumAlerts.forEach(alert => {
            report += `- **${alert.title}**: ${alert.message}\n`;
            if (alert.suggestion)
                report += `  💡 *${alert.suggestion}*\n`;
        });
        report += '\n';
    }
    if (lowAlerts.length > 0) {
        report += `## ℹ️ Low Priority Alerts\n`;
        lowAlerts.forEach(alert => {
            report += `- **${alert.title}**: ${alert.message}\n`;
            if (alert.suggestion)
                report += `  💡 *${alert.suggestion}*\n`;
        });
        report += '\n';
    }
    return report;
}
function getSeverityLevel(severity) {
    const levels = { low: 1, medium: 2, high: 3, critical: 4 };
    return levels[severity] || 1;
}
//# sourceMappingURL=index.js.map