#!/usr/bin/env php
<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use App\Framework\Core\Container;
use App\Framework\Performance\PerformanceDatabaseWorker;
use Pest\Support\Container;

$lockFile = sys_get_temp_dir() . '/performance_processing.lock';

// Lock-File prüfen um Doppelausführung zu verhindern
if (file_exists($lockFile)) {
    $lockTime = filemtime($lockFile);
    if (time() - $lockTime < 300) { // 5 Minuten Timeout
        echo "Performance log processing already running\n";
        exit(1);
    }
    // Altes Lock entfernen
    unlink($lockFile);
}

// Lock setzen
touch($lockFile);

try {
    $container = new Container();
    $worker = $container->get(PerformanceDatabaseWorker::class);

    $logFile = $argv[1] ?? null;

    if ($logFile && file_exists($logFile)) {
        echo "Processing specific log file: {$logFile}\n";
        $worker->processLogFile($logFile);
        echo "Processing completed\n";
    } else {
        // Alle pending Log-Dateien verarbeiten
        $logDir = $container->get('paths.storage') . '/logs/performance';
        $pattern = $logDir . '/performance-*.jsonl';
        $files = glob($pattern);

        echo "Found " . count($files) . " log files to process\n";

        foreach ($files as $file) {
            echo "Processing: " . basename($file) . "\n";
            $worker->processLogFile($file);
        }

        echo "All files processed\n";

        // Statistiken anzeigen
        $stats = $worker->getStatistics();
        if (!empty($stats)) {
            echo "\nStatistics (last 24h):\n";
            echo "Total requests: " . $stats['total_logs'] . "\n";
            echo "Avg response time: " . round($stats['avg_response_time'], 2) . "ms\n";
            echo "Max response time: " . round($stats['max_response_time'], 2) . "ms\n";
            echo "Avg memory: " . round($stats['avg_memory'], 2) . "MB\n";
            echo "Max memory: " . round($stats['max_memory'], 2) . "MB\n";
        }
    }

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
    exit(1);
} finally {
    // Lock entfernen
    if (file_exists($lockFile)) {
        unlink($lockFile);
    }
}

echo "Performance log processing completed\n";
exit(0);
