"use strict";
/**
 * Additional functions for enhanced performance module
 * These will be integrated into the main index.ts
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSystemHealthStatus = getSystemHealthStatus;
exports.emergencySystemRecovery = emergencySystemRecovery;
const enhanced_error_handler_1 = require("../utils/enhanced-error-handler");
const circuit_breaker_1 = require("./circuit-breaker");
const resource_leak_detector_1 = require("./resource-leak-detector");
const index_1 = require("./index");
/**
 * Initialize error reduction components
 */
function initializeErrorReduction(level) {
    // Always initialize enhanced error handler
    (0, enhanced_error_handler_1.getGlobalEnhancedErrorHandler)({
        enableRecovery: true,
        maxRetries: level === 'basic' ? 2 : level === 'standard' ? 3 : 5,
        trackMetrics: true,
        enableCircuitBreaker: level !== 'basic',
        enableResourceTracking: level === 'comprehensive'
    });
    // Initialize circuit breaker for standard and comprehensive levels
    if (level !== 'basic') {
        (0, circuit_breaker_1.getGlobalCircuitBreakerManager)();
    }
    // Initialize resource leak detection for comprehensive level
    if (level === 'comprehensive') {
        (0, resource_leak_detector_1.getGlobalResourceLeakDetector)({
            trackingEnabled: true,
            maxAge: 300000, // 5 minutes
            checkInterval: 30000, // 30 seconds
            enableStackTrace: true
        });
    }
}
/**
 * Enhanced shutdown with proper error handling
 */
async function shutdownPerformanceOptimizationsEnhanced() {
    return Promise.all([
        // Shutdown error reduction components first
        (0, enhanced_error_handler_1.shutdownGlobalEnhancedErrorHandler)(),
        (0, circuit_breaker_1.shutdownGlobalCircuitBreakerManager)(),
        (0, resource_leak_detector_1.shutdownGlobalResourceLeakDetector)(),
        // Then shutdown performance components
        // Note: These would need to be wrapped with proper error handling
    ]).then(() => {
        console.log('All performance optimizations shutdown successfully');
    }).catch(error => {
        console.error('Error during performance optimization shutdown:', error);
        throw error;
    });
}
/**
 * Get overall system health status
 */
function getSystemHealthStatus() {
    const issues = [];
    const recommendations = [];
    let totalScore = 100;
    try {
        // Check error handler health
        const errorHealth = (0, enhanced_error_handler_1.getGlobalEnhancedErrorHandler)().getHealthStatus();
        if (errorHealth.status === 'unhealthy') {
            totalScore -= 30;
            issues.push('High error rate detected');
            recommendations.push(...errorHealth.recommendations);
        }
        else if (errorHealth.status === 'degraded') {
            totalScore -= 15;
            issues.push('Elevated error rate');
        }
        // Check circuit breaker health
        const circuitHealth = (0, circuit_breaker_1.getGlobalCircuitBreakerManager)().getSystemHealth();
        if (circuitHealth.overallHealth < 70) {
            totalScore -= 20;
            issues.push(`${circuitHealth.openBreakers} circuit breakers open`);
            recommendations.push('Investigate failing operations');
        }
        // Check resource leak status
        const resourceStats = (0, resource_leak_detector_1.getGlobalResourceLeakDetector)().getResourceStats();
        if (resourceStats.potentialLeaks > 10) {
            totalScore -= 25;
            issues.push(`${resourceStats.potentialLeaks} potential resource leaks`);
            recommendations.push('Review resource cleanup patterns');
        }
        // Check memory pressure
        const memoryStats = (0, index_1.getGlobalMemoryOptimizer)().getDetailedStats();
        if (memoryStats.pressure.level > 0.8) {
            totalScore -= 20;
            issues.push('High memory pressure');
            recommendations.push('Consider reducing memory usage or increasing limits');
        }
    }
    catch (error) {
        totalScore -= 50;
        issues.push('Error collecting system health metrics');
        recommendations.push('Check system component initialization');
    }
    let status = 'healthy';
    if (totalScore < 50) {
        status = 'unhealthy';
    }
    else if (totalScore < 80) {
        status = 'degraded';
    }
    return {
        status,
        score: Math.max(0, totalScore),
        issues,
        recommendations
    };
}
/**
 * Emergency system recovery function
 */
async function emergencySystemRecovery() {
    const actions = [];
    const errors = [];
    try {
        // Force all circuit breakers to closed state
        const circuitBreaker = (0, circuit_breaker_1.getGlobalCircuitBreakerManager)();
        circuitBreaker.forceAllClosed();
        actions.push('Reset all circuit breakers to closed state');
        // Force garbage collection
        if (global.gc) {
            global.gc();
            actions.push('Forced garbage collection');
        }
        // Clean up resource leaks
        const leakDetector = (0, resource_leak_detector_1.getGlobalResourceLeakDetector)();
        const cleanedCount = leakDetector.forceCleanupAll();
        actions.push(`Cleaned up ${cleanedCount} tracked resources`);
        // Reset error metrics
        const errorHandler = (0, enhanced_error_handler_1.getGlobalEnhancedErrorHandler)();
        errorHandler.resetMetrics();
        actions.push('Reset error handler metrics');
        // Clear memory optimizer buffers
        const memoryOptimizer = (0, index_1.getGlobalMemoryOptimizer)();
        memoryOptimizer.forceGarbageCollection();
        actions.push('Cleared memory optimizer buffers');
        return { success: true, actions, errors };
    }
    catch (error) {
        errors.push(`Recovery action failed: ${error.message}`);
        return { success: false, actions, errors };
    }
}
//# sourceMappingURL=enhanced-index-additions.js.map