<?php

declare(strict_types=1);

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

use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\Performance\MemoryMonitor;
use App\Framework\Performance\PerformanceCategory;
use App\Framework\Performance\PerformanceConfig;
use App\Framework\Performance\PerformanceReporter;
use App\Framework\Performance\PerformanceService;

echo "=== Testing Performance Monitoring Integration ===\n\n";

echo "1. Testing Enhanced Performance Collector:\n";

try {
    $clock = new SystemClock();
    $highResClock = new SystemHighResolutionClock();
    $memoryMonitor = new MemoryMonitor();

    // Create collector with enabled = true for testing
    $collector = new EnhancedPerformanceCollector(
        $clock,
        $highResClock,
        $memoryMonitor,
        true // Enable for testing
    );

    echo "   ✅ EnhancedPerformanceCollector created\n";
    echo "      • Enabled: " . ($collector->isEnabled() ? 'Yes' : 'No') . "\n";
    echo "      • Total request time: " . number_format($collector->getTotalRequestTime(), 3) . "ms\n";

    // Test memory monitoring
    $memoryUsage = $collector->getTotalRequestMemory();
    $peakMemory = $collector->getPeakMemory();
    echo "      • Memory usage: " . number_format($memoryUsage / 1024 / 1024, 2) . " MB\n";
    echo "      • Peak memory: " . number_format($peakMemory / 1024 / 1024, 2) . " MB\n\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "2. Testing Performance Service Integration:\n";

try {
    $config = new PerformanceConfig(
        enabled: true,
        detailedReports: true,
        useEnhancedCollector: true,
        includeStackTrace: false,
        thresholds: [
            'slow_query_ms' => 100,
            'slow_request_ms' => 1000,
            'high_memory_mb' => 50,
        ],
        excludedPaths: ['/health', '/metrics', '/api']
    );

    $reporter = new PerformanceReporter($collector);
    $service = new PerformanceService($collector, $config, $reporter);

    echo "   ✅ PerformanceService created\n";
    echo "      • Service enabled: " . ($service->isEnabled() ? 'Yes' : 'No') . "\n";
    echo "      • Config thresholds: " . json_encode($config->getThresholds()) . "\n";
    echo "      • Excluded paths: " . json_encode($config->getExcludedPaths()) . "\n\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "3. Testing Performance Measurement:\n";

try {
    // Simulate some database operations
    $result1 = $service->measureDatabaseQuery('select', function () {
        usleep(50000); // 50ms

        return 'query result';
    }, ['table' => 'users', 'limit' => 10]);

    echo "   ✅ Database query measured\n";
    echo "      • Result: {$result1}\n";

    // Simulate cache operations
    $result2 = $service->measureCacheOperation('get', function () {
        usleep(10000); // 10ms

        return 'cached value';
    }, ['key' => 'user:123']);

    echo "   ✅ Cache operation measured\n";
    echo "      • Result: {$result2}\n";

    // Simulate view rendering
    $result3 = $service->measureViewRender('user.profile', function () {
        usleep(30000); // 30ms

        return '<html>rendered view</html>';
    }, ['user_id' => 123]);

    echo "   ✅ View render measured\n";
    echo "      • Result length: " . strlen($result3) . " chars\n\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "4. Testing Nested Performance Tracking:\n";

try {
    $service->startTiming('process_order', PerformanceCategory::CUSTOM, ['order_id' => 'ord_123']);

    // Nested operation 1
    $service->startTiming('validate_order', PerformanceCategory::CUSTOM, ['step' => 'validation']);
    usleep(20000); // 20ms
    $service->endTiming('validate_order');

    // Nested operation 2
    $service->startTiming('charge_payment', PerformanceCategory::API, ['gateway' => 'stripe']);
    usleep(100000); // 100ms
    $service->endTiming('charge_payment');

    // Nested operation 3
    $service->startTiming('send_confirmation', PerformanceCategory::CUSTOM, ['type' => 'email']);
    usleep(30000); // 30ms
    $service->endTiming('send_confirmation');

    $service->endTiming('process_order');

    echo "   ✅ Nested operations completed\n";
    echo "      • Call stack depth: {$collector->getCallStackDepth()}\n";
    echo "      • Active timers: " . implode(', ', $collector->getActiveTimers()) . "\n";
    echo "      • Total operations: " . count($collector->getNestedStructure()) . "\n\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "5. Testing Performance Reporting:\n";

try {
    $requestStats = $service->getRequestStats();
    echo "   📊 Request Statistics:\n";
    echo "      • Total time: " . number_format($requestStats['time_ms'], 3) . "ms\n";
    echo "      • Memory usage: " . number_format($requestStats['memory_bytes'] / 1024 / 1024, 2) . " MB\n";
    echo "      • Peak memory: " . number_format($requestStats['peak_memory_bytes'] / 1024 / 1024, 2) . " MB\n";
    echo "      • Metrics count: {$requestStats['metrics_count']}\n\n";

    // Get hierarchical report
    $hierarchicalReport = $collector->getHierarchicalReport();
    echo "   🌳 Hierarchical Report:\n";
    echo "      • Total operations: {$hierarchicalReport['total_operations']}\n";
    echo "      • Max call stack depth: {$hierarchicalReport['call_stack_depth']}\n";
    echo "      • Active operations: {$hierarchicalReport['active_operations']}\n\n";

    // Show execution tree
    $executionTree = $collector->getExecutionTree();
    echo "   🌲 Execution Tree:\n";
    echo $executionTree . "\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "6. Testing Performance Categories:\n";

try {
    $categories = [
        PerformanceCategory::DATABASE,
        PerformanceCategory::CACHE,
        PerformanceCategory::VIEW,
        PerformanceCategory::API,
        PerformanceCategory::CUSTOM,
        PerformanceCategory::SECURITY,
        PerformanceCategory::SYSTEM,
    ];

    echo "   📈 Performance by Category:\n";
    foreach ($categories as $category) {
        $metrics = $service->getMetrics($category);
        $count = count($metrics);
        if ($count > 0) {
            echo "      • {$category->value}: {$count} metrics\n";
            foreach ($metrics as $key => $metric) {
                $measurements = $metric->getMeasurements();
                $count = count($measurements);
                if ($count > 0) {
                    $totalTime = array_sum(array_map(fn ($m) => $m->getDuration()->toMilliseconds(), $measurements));
                    echo "        - {$key}: {$count} measurements, " . number_format($totalTime, 3) . "ms total\n";
                }
            }
        }
    }
    echo "\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "7. Testing Memory Monitor Integration:\n";

try {
    $memoryMonitor = new MemoryMonitor();
    $summary = $memoryMonitor->getSummary();

    echo "   💾 Memory Summary:\n";
    echo "      • Current: {$summary->current->toHumanReadable()}\n";
    echo "      • Peak: {$summary->peak->toHumanReadable()}\n";
    echo "      • Limit: {$summary->limit->toHumanReadable()}\n";
    echo "      • Usage: {$summary->usagePercentage->toString()}%\n";
    echo "      • Approaching limit: " . ($summary->isApproachingLimit ? 'Yes' : 'No') . "\n\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "8. Testing Performance Report Generation:\n";

try {
    $report = $service->generateReport('array');

    if (is_array($report) && ! empty($report)) {
        echo "   📋 Performance Report Generated:\n";
        echo "      • Report sections: " . implode(', ', array_keys($report)) . "\n";

        if (isset($report['summary'])) {
            echo "      • Summary available: Yes\n";
            $summary = $report['summary'];
            if (isset($summary['total_operations'])) {
                echo "      • Total operations: {$summary['total_operations']}\n";
            }
        }

        if (isset($report['metrics'])) {
            echo "      • Metrics count: " . count($report['metrics']) . "\n";
        }
    } else {
        echo "   ℹ️ No performance report generated (collector may be disabled)\n";
    }
    echo "\n";

    // Test slowest operations
    $slowest = $service->getSlowestOperations(5);
    echo "   🐌 Slowest Operations (Top 5):\n";
    foreach ($slowest as $i => $operation) {
        $duration = $operation['measurements']['total_duration_ms'] ?? 0;
        $name = $operation['key'] ?? 'unknown';
        echo "      " . ($i + 1) . ". {$name}: " . number_format($duration, 3) . "ms\n";
    }
    echo "\n";

} catch (\Throwable $e) {
    echo "   ❌ Error: {$e->getMessage()}\n\n";
}

echo "=== Performance Monitoring Integration Test Completed ===\n";
