/**
 * 🏥 VIGTHORIA HEALTH CHECK SYSTEM
 * Comprehensive monitoring and health validation for all services
 */

// Real VSCode import - No Mock!
const vscode = require('vscode');

const fetch = globalThis.fetch || ((...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args)));
const fs = require('fs').promises;
const os = require('os');

class HealthCheckSystem {
    constructor() {
        this.services = new Map();
        this.healthChecks = new Map(); // Initialize healthChecks Map
        this.healthHistory = new Map();
        this.alertThresholds = new Map();
        this.monitoringInterval = null;
        this.healthStatus = {
            overall: 'unknown',
            services: {},
            lastCheck: null,
            uptime: process.uptime()
        };
        
        // Initialize critical tracking properties
        this.startTime = Date.now();
        this.errorCount = 0;
        this.warningCount = 0;
        this.criticalIssues = 0;
        this.averageResponseTime = 0;
        this.lastCheckTime = 0;
        this.totalOperations = 0;
        
        this.initializeServices();
        this.setupMonitoring();
    }

    initializeServices() {
        // Core AI Services - Using localhost for development
        this.registerService('ollama', {
            url: 'http://localhost:11434',
            healthEndpoint: '/api/tags',
            timeout: 5000,
            critical: true,
            expectedResponse: null // Just check if response is OK
        });

        // Infrastructure Services - Using local server (VS Code server)
        this.registerService('main_server', {
            url: 'http://localhost:4005',
            healthEndpoint: '/',
            timeout: 3000,
            critical: true,
            expectedResponse: null // Just check if server responds
        });

        // Extension API Server
        this.registerService('extension_api', {
            url: 'http://localhost:8002',
            healthEndpoint: '/health',
            timeout: 3000,
            critical: false,
            expectedResponse: { status: 'healthy' }
        });

        // Extension API (if deployed)
        this.registerService('extension_api', {
            url: 'https://extension.vigthoria.io',
            healthEndpoint: '/health',
            timeout: 5000,
            critical: false,
            expectedResponse: { status: 'healthy' }
        });

        console.log(`🏥 Health check system initialized for ${this.services.size} services`);
    }

    registerService(serviceName, config) {
        this.services.set(serviceName, {
            ...config,
            lastCheck: null,
            status: 'unknown',
            consecutiveFailures: 0,
            uptimePercentage: 100,
            responseTime: null
        });

        // Set alert thresholds (relaxed for stability)
        this.alertThresholds.set(serviceName, {
            consecutiveFailures: config.critical ? 20 : 50, // Increased thresholds
            responseTimeThreshold: config.timeout * 1.5, // More lenient
            uptimeThreshold: config.critical ? 50 : 40 // Very relaxed - only alert on sustained downtime
        });
    }

    setupMonitoring() {
        // Initial health check
        this.performHealthCheck();
        
        // Set up periodic monitoring (every 5 minutes for stability)
        this.monitoringInterval = setInterval(() => {
            this.performHealthCheck();
        }, 300000); // Reduced from 30s to 5 minutes

        // VS Code workspace monitoring
        this.setupWorkspaceMonitoring();
        
        // System resource monitoring
        this.setupResourceMonitoring();
    }

    async performHealthCheck() {
        console.log('🏥 Performing comprehensive health check...');
        
        const checkPromises = Array.from(this.services.entries()).map(
            ([serviceName, config]) => this.checkServiceHealth(serviceName, config)
        );

        const results = await Promise.allSettled(checkPromises);
        
        // Update overall health status
        this.updateOverallHealth(results);
        
        // Check for alerts
        this.checkAlerts();
        
        // Update health history
        this.updateHealthHistory();
        
        this.healthStatus.lastCheck = new Date().toISOString();
        
        console.log(`🏥 Health check completed. Overall status: ${this.healthStatus.overall}`);
        
        return this.getHealthReport();
    }

    async checkServiceHealth(serviceName, config) {
        const startTime = Date.now();
        
        try {
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), config.timeout);
            
            const response = await fetch(config.url + config.healthEndpoint, {
                method: 'GET',
                signal: controller.signal,
                headers: {
                    'User-Agent': 'Vigthoria-Health-Check/2.0',
                    'Accept': 'application/json'
                }
            });
            
            clearTimeout(timeoutId);
            
            const responseTime = Date.now() - startTime;
            const responseData = await response.json().catch(() => ({}));
            
            if (response.ok && this.validateExpectedResponse(responseData, config.expectedResponse)) {
                this.recordSuccess(serviceName, responseTime);
                return {
                    service: serviceName,
                    status: 'healthy',
                    responseTime,
                    data: responseData
                };
            } else {
                this.recordFailure(serviceName, `HTTP ${response.status}`);
                return {
                    service: serviceName,
                    status: 'unhealthy',
                    error: `HTTP ${response.status}`,
                    responseTime
                };
            }
            
        } catch (error) {
            const responseTime = Date.now() - startTime;
            this.recordFailure(serviceName, error.message);
            
            return {
                service: serviceName,
                status: 'error',
                error: error.message,
                responseTime
            };
        }
    }

    validateExpectedResponse(actual, expected) {
        if (!expected) return true; // No validation required if no expected response
        
        // Simple validation - check if expected keys exist with correct values
        for (const [key, value] of Object.entries(expected)) {
            if (actual[key] !== value) {
                return false;
            }
        }
        
        return true;
    }

    recordSuccess(serviceName, responseTime) {
        const service = this.services.get(serviceName);
        if (service) {
            service.status = 'healthy';
            service.consecutiveFailures = 0;
            service.responseTime = responseTime;
            service.lastCheck = new Date().toISOString();
            
            // Update uptime percentage
            this.updateUptimePercentage(serviceName, true);
        }
    }

    recordFailure(serviceName, error) {
        const service = this.services.get(serviceName);
        if (service) {
            service.status = 'unhealthy';
            service.consecutiveFailures++;
            service.lastError = error;
            service.lastCheck = new Date().toISOString();
            
            // Update uptime percentage
            this.updateUptimePercentage(serviceName, false);
        }
    }

    updateUptimePercentage(serviceName, success) {
        const service = this.services.get(serviceName);
        if (!service) return;
        
        // Simple rolling average calculation
        const currentUptime = service.uptimePercentage || 100;
        const weight = 0.03; // Low weight - resilient to brief outages
        
        if (success) {
            service.uptimePercentage = currentUptime * (1 - weight) + 100 * weight;
        } else {
            service.uptimePercentage = currentUptime * (1 - weight) + 0 * weight;
        }
    }

    updateOverallHealth(results) {
        const serviceResults = results.map(result => result.value || result.reason);
        const criticalServices = Array.from(this.services.entries())
            .filter(([name, config]) => config.critical)
            .map(([name]) => name);
        
        const criticalServiceResults = serviceResults.filter(result => 
            criticalServices.includes(result.service)
        );
        
        // Check critical services first
        const criticalFailures = criticalServiceResults.filter(result => 
            result.status !== 'healthy'
        );
        
        if (criticalFailures.length > 0) {
            this.healthStatus.overall = 'critical';
        } else {
            const allFailures = serviceResults.filter(result => 
                result.status !== 'healthy'
            );
            
            if (allFailures.length === 0) {
                this.healthStatus.overall = 'healthy';
            } else if (allFailures.length <= serviceResults.length * 0.3) {
                this.healthStatus.overall = 'degraded';
            } else {
                this.healthStatus.overall = 'unhealthy';
            }
        }
        
        // Update service statuses
        serviceResults.forEach(result => {
            this.healthStatus.services[result.service] = {
                status: result.status,
                responseTime: result.responseTime,
                error: result.error,
                lastCheck: new Date().toISOString()
            };
        });
    }

    checkAlerts() {
        for (const [serviceName, service] of this.services.entries()) {
            const thresholds = this.alertThresholds.get(serviceName);
            if (!thresholds) continue;
            
            // Check consecutive failures
            if (service.consecutiveFailures >= thresholds.consecutiveFailures) {
                this.triggerAlert('consecutive_failures', serviceName, {
                    failures: service.consecutiveFailures,
                    threshold: thresholds.consecutiveFailures
                });
            }
            
            // Check response time
            if (service.responseTime && service.responseTime > thresholds.responseTimeThreshold) {
                this.triggerAlert('slow_response', serviceName, {
                    responseTime: service.responseTime,
                    threshold: thresholds.responseTimeThreshold
                });
            }
            
            // Check uptime percentage
            if (service.uptimePercentage < thresholds.uptimeThreshold) {
                this.triggerAlert('low_uptime', serviceName, {
                    uptime: service.uptimePercentage,
                    threshold: thresholds.uptimeThreshold
                });
            }
        }
    }

    triggerAlert(alertType, serviceName, details) {
        const alert = {
            type: alertType,
            service: serviceName,
            timestamp: new Date().toISOString(),
            details: details,
            severity: this.getAlertSeverity(alertType, serviceName)
        };
        
        console.warn(`🚨 Health Alert [${alert.severity}]: ${alertType} for ${serviceName}`, details);
        
        // Show user notification for critical alerts
        if (alert.severity === 'critical') {
            this.showCriticalAlert(alert);
        }
        
        // Store alert for history
        this.storeAlert(alert);
    }

    getAlertSeverity(alertType, serviceName) {
        const service = this.services.get(serviceName);
        const isCritical = service?.critical || false;
        
        const severityMap = {
            'consecutive_failures': isCritical ? 'critical' : 'warning',
            'slow_response': 'warning',
            'low_uptime': isCritical ? 'critical' : 'warning'
        };
        
        return severityMap[alertType] || 'info';
    }

    showCriticalAlert(alert) {
        const message = `Critical service issue detected: ${alert.service} - ${alert.type}`;
        
        vscode.window.showErrorMessage(
            message,
            'View Details',
            'Health Dashboard'
        ).then(selection => {
            if (selection === 'View Details') {
                this.showAlertDetails(alert);
            } else if (selection === 'Health Dashboard') {
                this.openHealthDashboard();
            }
        });
    }

    showAlertDetails(alert) {
        const details = `
Vigthoria AI Health Alert

Service: ${alert.service}
Alert Type: ${alert.type}
Severity: ${alert.severity}
Time: ${alert.timestamp}

Details:
${JSON.stringify(alert.details, null, 2)}

Recommended Actions:
${this.getRecommendedActions(alert)}
        `;
        
        vscode.workspace.openTextDocument({
            content: details,
            language: 'text'
        }).then(doc => {
            vscode.window.showTextDocument(doc);
        });
    }

    getRecommendedActions(alert) {
        const actionMap = {
            'consecutive_failures': `
- Check network connectivity
- Verify service is running on the server
- Contact system administrator if issue persists`,
            'slow_response': `
- Monitor server performance
- Check network latency
- Consider switching to alternative service`,
            'low_uptime': `
- Review service stability
- Consider infrastructure improvements
- Enable fallback mechanisms`
        };
        
        return actionMap[alert.type] || 'Contact technical support for assistance.';
    }

    storeAlert(alert) {
        // Store in memory for now (could be persisted to file)
        if (!this.alertHistory) {
            this.alertHistory = [];
        }
        
        this.alertHistory.push(alert);
        
        // Keep only last 100 alerts
        if (this.alertHistory.length > 100) {
            this.alertHistory = this.alertHistory.slice(-100);
        }
    }

    updateHealthHistory() {
        const timestamp = Date.now();
        const snapshot = {
            timestamp: timestamp,
            overall: this.healthStatus.overall,
            services: { ...this.healthStatus.services }
        };
        
        this.healthHistory.set(timestamp, snapshot);
        
        // Keep only last 24 hours of history (assuming checks every 30 seconds)
        const cutoff = timestamp - (24 * 60 * 60 * 1000);
        for (const [key] of this.healthHistory.entries()) {
            if (key < cutoff) {
                this.healthHistory.delete(key);
            }
        }
    }

    setupWorkspaceMonitoring() {
        // Monitor workspace file system health
        setInterval(async () => {
            await this.checkWorkspaceHealth();
        }, 60000); // Check every minute
    }

    async checkWorkspaceHealth() {
        try {
            const workspaceFolders = vscode.workspace.workspaceFolders;
            if (!workspaceFolders || workspaceFolders.length === 0) {
                return;
            }
            
            const workspacePath = workspaceFolders[0].uri.fsPath;
            
            // Check if workspace is accessible
            await fs.access(workspacePath);
            
            // Check disk space (simplified)
            const stats = await fs.stat(workspacePath);
            
            // Update workspace health status
            this.healthStatus.workspace = {
                accessible: true,
                path: workspacePath,
                lastCheck: new Date().toISOString()
            };
            
        } catch (error) {
            this.healthStatus.workspace = {
                accessible: false,
                error: error.message,
                lastCheck: new Date().toISOString()
            };
            
            this.triggerAlert('workspace_error', 'workspace', {
                error: error.message
            });
        }
    }

    setupResourceMonitoring() {
        // Monitor system resources every 2 minutes
        setInterval(() => {
            this.checkSystemResources();
        }, 120000);
    }

    checkSystemResources() {
        const resources = {
            memory: {
                total: os.totalmem(),
                free: os.freemem(),
                used: os.totalmem() - os.freemem(),
                percentage: ((os.totalmem() - os.freemem()) / os.totalmem()) * 100
            },
            cpu: {
                cores: os.cpus().length,
                loadavg: os.loadavg(),
                uptime: os.uptime()
            },
            platform: os.platform(),
            arch: os.arch(),
            nodeVersion: process.version,
            processUptime: process.uptime()
        };
        
        this.healthStatus.resources = resources;
        
        // Check for resource alerts
        if (resources.memory.percentage > 90) {
            this.triggerAlert('high_memory_usage', 'system', {
                usage: resources.memory.percentage
            });
        }
        
        if (resources.cpu.loadavg[0] > resources.cpu.cores * 2) {
            this.triggerAlert('high_cpu_load', 'system', {
                load: resources.cpu.loadavg[0],
                cores: resources.cpu.cores
            });
        }
    }

    getHealthReport() {
        return {
            overall: this.healthStatus.overall,
            services: Object.fromEntries(
                Array.from(this.services.entries()).map(([name, service]) => [
                    name,
                    {
                        status: service.status,
                        responseTime: service.responseTime,
                        consecutiveFailures: service.consecutiveFailures,
                        uptimePercentage: Math.round(service.uptimePercentage * 100) / 100,
                        lastCheck: service.lastCheck,
                        critical: service.critical
                    }
                ])
            ),
            resources: this.healthStatus.resources,
            workspace: this.healthStatus.workspace,
            lastCheck: this.healthStatus.lastCheck,
            alerts: this.alertHistory?.slice(-10) || []
        };
    }

    async getDetailedHealthReport() {
        const report = this.getHealthReport();
        
        // Add historical data
        report.history = Array.from(this.healthHistory.values()).slice(-100);
        
        // Add service-specific diagnostics
        report.diagnostics = {};
        for (const [serviceName, service] of this.services.entries()) {
            report.diagnostics[serviceName] = await this.runServiceDiagnostics(serviceName);
        }
        
        return report;
    }

    async runServiceDiagnostics(serviceName) {
        const service = this.services.get(serviceName);
        if (!service) return null;
        
        return {
            connectivity: await this.testConnectivity(service.url),
            dns: await this.testDNSResolution(service.url),
            ssl: await this.testSSLCertificate(service.url),
            responseHeaders: await this.getResponseHeaders(service.url + service.healthEndpoint)
        };
    }

    async testConnectivity(url) {
        try {
            const response = await fetch(url, { 
                method: 'HEAD', 
                timeout: 3000 
            });
            return { success: true, status: response.status };
        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    async testDNSResolution(url) {
        try {
            const hostname = new URL(url).hostname;
            // Simplified DNS test (would need dns module for full implementation)
            return { success: true, hostname };
        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    async testSSLCertificate(url) {
        if (!url.startsWith('https://')) {
            return { applicable: false };
        }
        
        try {
            // Simplified SSL test
            const response = await fetch(url, { method: 'HEAD' });
            return { success: true, secure: true };
        } catch (error) {
            return { success: false, error: error.message };
        }
    }

    async getResponseHeaders(url) {
        try {
            const response = await fetch(url, { method: 'HEAD' });
            const headers = {};
            for (const [key, value] of response.headers.entries()) {
                headers[key] = value;
            }
            return headers;
        } catch (error) {
            return { error: error.message };
        }
    }

    openHealthDashboard() {
        // Create a webview with health dashboard
        const panel = vscode.window.createWebviewPanel(
            'vigthoriaHealth',
            'Vigthoria AI Health Dashboard',
            vscode.ViewColumn.One,
            { enableScripts: true }
        );
        
        panel.webview.html = this.generateHealthDashboardHTML();
    }

    generateHealthDashboardHTML() {
        const report = this.getHealthReport();
        
        return `<!DOCTYPE html>
        <html>
        <head>
            <title>Vigthoria AI Health Dashboard</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                .status-healthy { color: #28a745; }
                .status-degraded { color: #ffc107; }
                .status-unhealthy { color: #dc3545; }
                .status-critical { color: #dc3545; font-weight: bold; }
                .service { margin: 10px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px; }
                .metric { margin: 5px 0; }
            </style>
        </head>
        <body>
            <h1>🏥 Vigthoria AI Health Dashboard</h1>
            <h2>Overall Status: <span class="status-${report.overall}">${report.overall.toUpperCase()}</span></h2>
            
            <h3>Services</h3>
            ${Object.entries(report.services).map(([name, service]) => `
                <div class="service">
                    <h4>${name} <span class="status-${service.status}">${service.status}</span></h4>
                    <div class="metric">Response Time: ${service.responseTime || 'N/A'}ms</div>
                    <div class="metric">Uptime: ${service.uptimePercentage || 'N/A'}%</div>
                    <div class="metric">Failures: ${service.consecutiveFailures}</div>
                    <div class="metric">Last Check: ${service.lastCheck || 'Never'}</div>
                </div>
            `).join('')}
            
            <h3>System Resources</h3>
            ${report.resources ? `
                <div class="metric">Memory Usage: ${Math.round(report.resources.memory.percentage)}%</div>
                <div class="metric">CPU Cores: ${report.resources.cpu.cores}</div>
                <div class="metric">System Uptime: ${Math.round(report.resources.cpu.uptime / 3600)}h</div>
            ` : 'Resource monitoring not available'}
            
            <p><small>Last updated: ${report.lastCheck}</small></p>
        </body>
        </html>`;
    }

    destroy() {
        if (this.monitoringInterval) {
            clearInterval(this.monitoringInterval);
        }
    }

    /**
     * Get comprehensive health and performance metrics
     * Required by optimization manager for system monitoring
     */
    getMetrics() {
        try {
            const timestamp = Date.now();
            
            // Calculate system health scores
            const healthScore = this.calculateOverallHealth();
            const performanceScore = this.calculatePerformanceScore();
            const stabilityScore = this.calculateStabilityScore();
            
            // Memory and performance metrics
            const memoryMetrics = this.getMemoryMetrics();
            const performanceMetrics = this.getPerformanceMetrics();
            
            // Build comprehensive metrics
            const metrics = {
                timestamp: timestamp,
                overall: {
                    health: healthScore,
                    performance: performanceScore,
                    stability: stabilityScore,
                    status: this.getOverallStatus(healthScore, performanceScore, stabilityScore)
                },
                system: {
                    uptime: timestamp - this.startTime,
                    checks: this.healthChecks.size,
                    errors: this.errorCount,
                    warnings: this.warningCount,
                    lastCheck: this.lastCheckTime
                },
                memory: memoryMetrics,
                performance: performanceMetrics,
                components: this.getComponentMetrics(),
                trends: this.getTrendMetrics(),
                alerts: this.getActiveAlerts()
            };
            
            // Update metrics history
            this.updateMetricsHistory(metrics);
            
            return metrics;
            
        } catch (error) {
            console.error('❌ Failed to get health metrics:', error);
            return this.getEmergencyMetrics();
        }
    }

    /**
     * Calculate overall system health score (0-100)
     */
    calculateOverallHealth() {
        if (this.healthChecks.size === 0) {
            return 50; // Default when no checks available
        }

        let totalScore = 0;
        let checkCount = 0;

        for (const [component, status] of this.healthChecks) {
            if (status && typeof status.health === 'number') {
                totalScore += status.health;
                checkCount++;
            } else if (status && status.status) {
                // Convert status to score
                const score = this.statusToScore(status.status);
                totalScore += score;
                checkCount++;
            }
        }

        return checkCount > 0 ? Math.round(totalScore / checkCount) : 75;
    }

    /**
     * Calculate performance score based on response times and efficiency
     */
    calculatePerformanceScore() {
        const avgResponseTime = this.averageResponseTime;
        const recentErrors = this.errorCount;
        
        // Base score from response time (lower is better)
        let performanceScore = 100;
        if (avgResponseTime > 100) performanceScore -= Math.min(30, (avgResponseTime - 100) / 10);
        if (avgResponseTime > 500) performanceScore -= 20;
        if (avgResponseTime > 1000) performanceScore -= 30;
        
        // Reduce score for recent errors
        performanceScore -= Math.min(25, recentErrors * 2);
        
        return Math.max(0, Math.round(performanceScore));
    }

    /**
     * Calculate stability score based on error patterns and consistency
     */
    calculateStabilityScore() {
        const uptime = Date.now() - this.startTime;
        const hoursSinceStart = uptime / (1000 * 60 * 60);
        const errorsPerHour = hoursSinceStart > 0 ? this.errorCount / hoursSinceStart : 0;
        
        let stabilityScore = 100;
        
        // Reduce for error frequency
        if (errorsPerHour > 0.1) stabilityScore -= 20;
        if (errorsPerHour > 0.5) stabilityScore -= 30;
        if (errorsPerHour > 1) stabilityScore -= 30;
        
        // Reduce for recent critical issues
        if (this.criticalIssues > 0) stabilityScore -= this.criticalIssues * 15;
        
        return Math.max(0, Math.round(stabilityScore));
    }

    /**
     * Convert status string to numeric score
     */
    statusToScore(status) {
        const statusMap = {
            'healthy': 100,
            'good': 85,
            'warning': 60,
            'error': 20,
            'critical': 5,
            'unknown': 50
        };
        
        return statusMap[status?.toLowerCase()] || 50;
    }

    /**
     * Get overall system status from scores
     */
    getOverallStatus(health, performance, stability) {
        const avgScore = (health + performance + stability) / 3;
        
        if (avgScore >= 90) return 'excellent';
        if (avgScore >= 75) return 'good';
        if (avgScore >= 60) return 'warning';
        if (avgScore >= 30) return 'error';
        return 'critical';
    }

    /**
     * Get memory usage metrics
     */
    getMemoryMetrics() {
        try {
            if (typeof process !== 'undefined' && process.memoryUsage) {
                const usage = process.memoryUsage();
                return {
                    heapUsed: Math.round(usage.heapUsed / 1024 / 1024 * 100) / 100,
                    heapTotal: Math.round(usage.heapTotal / 1024 / 1024 * 100) / 100,
                    external: Math.round(usage.external / 1024 / 1024 * 100) / 100,
                    rss: Math.round(usage.rss / 1024 / 1024 * 100) / 100,
                    units: 'MB'
                };
            }
        } catch (error) {
            console.warn('Memory metrics unavailable:', error.message);
        }
        
        return {
            heapUsed: 0,
            heapTotal: 0,
            external: 0,
            rss: 0,
            units: 'MB',
            available: false
        };
    }

    /**
     * Get performance metrics
     */
    getPerformanceMetrics() {
        return {
            averageResponseTime: this.averageResponseTime || 0,
            operationsPerSecond: this.calculateOPS(),
            throughput: this.calculateThroughput(),
            efficiency: this.calculateEfficiency(),
            bottlenecks: this.identifyBottlenecks()
        };
    }

    /**
     * Get individual component metrics
     */
    getComponentMetrics() {
        const components = {};
        
        for (const [name, status] of this.healthChecks) {
            components[name] = {
                status: status?.status || 'unknown',
                health: status?.health || 50,
                lastCheck: status?.lastCheck || 0,
                details: status?.details || {}
            };
        }
        
        return components;
    }

    /**
     * Get trend metrics for analysis
     */
    getTrendMetrics() {
        return {
            healthTrend: this.calculateHealthTrend(),
            performanceTrend: this.calculatePerformanceTrend(),
            errorTrend: this.calculateErrorTrend(),
            timeWindow: '1h'
        };
    }

    /**
     * Get active alerts and warnings
     */
    getActiveAlerts() {
        const alerts = [];
        
        // Check for critical health issues
        if (this.criticalIssues > 0) {
            alerts.push({
                level: 'critical',
                message: `${this.criticalIssues} critical issue(s) detected`,
                timestamp: Date.now()
            });
        }
        
        // Check for high error rate
        if (this.errorCount > 10) {
            alerts.push({
                level: 'warning',
                message: `High error count: ${this.errorCount}`,
                timestamp: Date.now()
            });
        }
        
        // Check for slow response times
        if (this.averageResponseTime > 1000) {
            alerts.push({
                level: 'warning',
                message: `Slow response time: ${this.averageResponseTime}ms`,
                timestamp: Date.now()
            });
        }
        
        return alerts;
    }

    /**
     * Calculate operations per second
     */
    calculateOPS() {
        const timeDiff = Date.now() - this.startTime;
        const operations = this.totalOperations || 0;
        return timeDiff > 0 ? Math.round((operations / timeDiff) * 1000) : 0;
    }

    /**
     * Calculate system throughput
     */
    calculateThroughput() {
        return {
            requests: this.totalOperations || 0,
            successful: (this.totalOperations || 0) - this.errorCount,
            failed: this.errorCount,
            successRate: this.totalOperations > 0 ? 
                Math.round(((this.totalOperations - this.errorCount) / this.totalOperations) * 100) : 100
        };
    }

    /**
     * Calculate system efficiency
     */
    calculateEfficiency() {
        const successRate = this.calculateThroughput().successRate;
        const responseTime = this.averageResponseTime || 100;
        
        // Efficiency based on success rate and response time
        let efficiency = successRate;
        if (responseTime > 200) efficiency *= 0.9;
        if (responseTime > 500) efficiency *= 0.8;
        if (responseTime > 1000) efficiency *= 0.7;
        
        return Math.round(efficiency);
    }

    /**
     * Identify system bottlenecks
     */
    identifyBottlenecks() {
        const bottlenecks = [];
        
        if (this.averageResponseTime > 500) {
            bottlenecks.push('high_latency');
        }
        
        if (this.errorCount > 5) {
            bottlenecks.push('error_rate');
        }
        
        const memoryMetrics = this.getMemoryMetrics();
        if (memoryMetrics.heapUsed > 100) {
            bottlenecks.push('memory_usage');
        }
        
        return bottlenecks;
    }

    /**
     * Calculate health trend
     */
    calculateHealthTrend() {
        // Simplified trend calculation
        const currentHealth = this.calculateOverallHealth();
        const previousHealth = this.previousHealth || currentHealth;
        
        this.previousHealth = currentHealth;
        
        if (currentHealth > previousHealth + 5) return 'improving';
        if (currentHealth < previousHealth - 5) return 'declining';
        return 'stable';
    }

    /**
     * Calculate performance trend
     */
    calculatePerformanceTrend() {
        const currentPerf = this.calculatePerformanceScore();
        const previousPerf = this.previousPerformance || currentPerf;
        
        this.previousPerformance = currentPerf;
        
        if (currentPerf > previousPerf + 5) return 'improving';
        if (currentPerf < previousPerf - 5) return 'declining';
        return 'stable';
    }

    /**
     * Calculate error trend
     */
    calculateErrorTrend() {
        const currentErrors = this.errorCount;
        const previousErrors = this.previousErrors || currentErrors;
        
        this.previousErrors = currentErrors;
        
        if (currentErrors < previousErrors) return 'decreasing';
        if (currentErrors > previousErrors) return 'increasing';
        return 'stable';
    }

    /**
     * Update metrics history for trend analysis
     */
    updateMetricsHistory(metrics) {
        if (!this.metricsHistory) {
            this.metricsHistory = [];
        }
        
        this.metricsHistory.push({
            timestamp: metrics.timestamp,
            health: metrics.overall.health,
            performance: metrics.overall.performance,
            stability: metrics.overall.stability
        });
        
        // Keep only last 100 entries
        if (this.metricsHistory.length > 100) {
            this.metricsHistory = this.metricsHistory.slice(-100);
        }
    }

    /**
     * Get emergency metrics when main collection fails
     */
    getEmergencyMetrics() {
        return {
            timestamp: Date.now(),
            overall: {
                health: 25,
                performance: 25,
                stability: 25,
                status: 'emergency'
            },
            system: {
                uptime: Date.now() - this.startTime,
                checks: 0,
                errors: this.errorCount || 0,
                warnings: this.warningCount || 0,
                lastCheck: 0
            },
            emergency: true,
            message: 'Health check system in emergency mode'
        };
    }
}

module.exports = { HealthCheckSystem };
