<?php
/**
 * Bootstrap File for Concurrency Optimizations
 * Include this in your main index.php or bootstrap file
 */

// Load optimization classes
require_once APP_ROOT . '/core/Cache.php';
require_once APP_ROOT . '/core/CacheInvalidator.php';
require_once APP_ROOT . '/core/RateLimiter.php';
require_once APP_ROOT . '/core/SessionHandler.php';
require_once APP_ROOT . '/core/PerformanceMonitor.php';
require_once APP_ROOT . '/core/UploadOptimizer.php';
require_once APP_ROOT . '/core/RedisCache.php'; // For enterprise-scale caching
require_once APP_ROOT . '/core/OptimisticLock.php'; // For high-concurrency stock operations

// Initialize optimizations based on configuration

/**
 * Initialize all concurrency optimizations
 */
function initConcurrencyOptimizations(): void {
    // Initialize performance monitoring
    if (APP_DEBUG) {
        PerformanceMonitor::start();
    }
    
    // Initialize optimized session handler
    if (SESSION_HANDLER === 'files') {
        initOptimizedSession();
    }
    
    // Create necessary directories
    $directories = [
        defined('CACHE_PATH') ? CACHE_PATH : (APP_ROOT . '/storage/cache'),
        defined('SESSION_PATH') ? SESSION_PATH : (APP_ROOT . '/storage/sessions'),
        defined('RATELIMIT_PATH') ? RATELIMIT_PATH : (APP_ROOT . '/storage/ratelimit'),
        defined('LOGS_PATH') ? LOGS_PATH : (APP_ROOT . '/storage/logs'),
        UPLOAD_PATH
    ];
    
    foreach ($directories as $dir) {
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
    }
    
    // Register shutdown function for cleanup and logging
    register_shutdown_function('handleShutdown');
}

/**
 * Handle application shutdown for cleanup and logging
 */
function handleShutdown(): void {
    if (APP_DEBUG) {
        // Log slow queries
        PerformanceMonitor::logSlowQueries();
        
        // Log performance metrics
        $metrics = PerformanceMonitor::getMetrics();
        if ($metrics['execution_time'] > 1000) { // Log if execution time > 1 second
            $logFile = defined('LOGS_PATH') ? LOGS_PATH . '/performance.log' : (APP_ROOT . '/storage/logs/performance.log');
            $logDir = dirname($logFile);
            
            if (!is_dir($logDir)) {
                mkdir($logDir, 0755, true);
            }
            
            $entry = date('Y-m-d H:i:s') . " - " . json_encode($metrics) . "\n";
            file_put_contents($logFile, $entry, FILE_APPEND);
        }
    }
}

/**
 * Apply rate limiting to current request
 */
function applyRateLimit(string $identifier = null, string $type = 'default'): bool {
    $identifier = $identifier ?? ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    
    if (!RateLimiter::attempt($identifier, $type)) {
        http_response_code(429);
        echo json_encode([
            'error' => 'Too many requests',
            'retry_after' => RateLimiter::resetAt($identifier, $type) - time()
        ]);
        exit;
    }
    
    return true;
}

/**
 * Get performance metrics (for debugging)
 */
function getPerformanceMetrics(): array {
    return PerformanceMonitor::getMetrics();
}

// Auto-initialize if this file is included directly
if (basename(__FILE__) === basename($_SERVER['SCRIPT_NAME'])) {
    initConcurrencyOptimizations();
    echo "Concurrency optimizations initialized successfully.\n";
    echo "Performance metrics: " . json_encode(getPerformanceMetrics()) . "\n";
}
