<?php
/**
 * Performance Monitor for High Concurrency
 * Tracks and logs performance metrics
 */
class PerformanceMonitor {
    private static array $metrics = [];
    private static float $startTime;
    
    public static function start(): void {
        self::$startTime = microtime(true);
        self::$metrics = [
            'queries' => 0,
            'cache_hits' => 0,
            'cache_misses' => 0,
            'slow_queries' => []
        ];
    }
    
    public static function logQuery(string $sql, float $executionTime): void {
        self::$metrics['queries']++;
        
        if ($executionTime > 0.1) { // Log queries slower than 100ms
            self::$metrics['slow_queries'][] = [
                'sql' => substr($sql, 0, 200),
                'time' => $executionTime
            ];
        }
    }
    
    public static function logCacheHit(): void {
        self::$metrics['cache_hits']++;
    }
    
    public static function logCacheMiss(): void {
        self::$metrics['cache_misses']++;
    }
    
    public static function getMetrics(): array {
        $executionTime = microtime(true) - self::$startTime;
        
        return [
            'execution_time' => round($executionTime * 1000, 2), // in ms
            'queries' => self::$metrics['queries'],
            'cache_hits' => self::$metrics['cache_hits'],
            'cache_misses' => self::$metrics['cache_misses'],
            'cache_hit_rate' => self::$metrics['cache_hits'] + self::$metrics['cache_misses'] > 0
                ? round((self::$metrics['cache_hits'] / (self::$metrics['cache_hits'] + self::$metrics['cache_misses'])) * 100, 2)
                : 0,
            'slow_queries' => count(self::$metrics['slow_queries']),
            'memory_usage' => round(memory_get_peak_usage() / 1024 / 1024, 2) // in MB
        ];
    }
    
    public static function logSlowQueries(): void {
        if (!empty(self::$metrics['slow_queries']) && APP_DEBUG) {
            $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(self::$metrics['slow_queries']) . "\n";
            file_put_contents($logFile, $entry, FILE_APPEND);
        }
    }
}

/**
 * Initialize performance monitoring (call at start of request)
 */
function initPerformanceMonitoring(): void {
    if (APP_DEBUG) {
        PerformanceMonitor::start();
    }
}
