<?php

declare(strict_types=1);

/**
 * LiveComponent Action Profiling Usage Examples
 *
 * Dieses Script demonstriert die erweiterten Action-Profiling-Funktionen
 * mit dem ActionProfiler für detaillierte Performance-Analyse.
 *
 * Ausführung: php examples/action-profiling-usage.php
 */

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

use App\Framework\Performance\NestedPerformanceTracker;
use App\Framework\LiveComponents\Performance\ActionProfiler;
use App\Framework\LiveComponents\ValueObjects\ComponentId;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;

// Initialize tracker and profiler
$tracker = new NestedPerformanceTracker(
    new SystemClock(),
    new SystemHighResolutionClock(),
    new MemoryMonitor()
);

$profiler = new ActionProfiler($tracker);

echo "=== LiveComponent Action Profiling Examples ===\n\n";

// Example 1: Profiling einzelner Action Execution
echo "Example 1: Detailed Action Execution Profiling\n";
echo str_repeat('-', 50) . "\n";

$componentId = ComponentId::create('counter', 'demo-123');

// Simuliere vollständige Action Execution mit allen Sicherheits-Checks
$profiler->profileCsrfValidation(
    $componentId,
    'increment',
    function () {
        usleep(200); // 0.2ms - CSRF validation
    }
);

$profiler->profileAuthorizationCheck(
    $componentId,
    'increment',
    function () {
        usleep(300); // 0.3ms - Authorization check
    }
);

$profiler->profileRateLimitCheck(
    $componentId,
    'increment',
    function () {
        usleep(150); // 0.15ms - Rate limit check
    }
);

$profiler->profileParameterBinding(
    $componentId,
    'increment',
    function () {
        usleep(400); // 0.4ms - Parameter binding with reflection
        return ['value' => 1];
    }
);

// Haupte Action execution (simuliert in executeActionAndBuildUpdate)
$tracker->measure(
    "livecomponent.counter.increment",
    \App\Framework\Performance\PerformanceCategory::CUSTOM,
    function () use ($tracker) {
        $tracker->measure(
            "livecomponent.action.execute",
            \App\Framework\Performance\PerformanceCategory::CUSTOM,
            function () {
                usleep(2000); // 2ms - Business logic
            }
        );

        $tracker->measure(
            "livecomponent.state.validate",
            \App\Framework\Performance\PerformanceCategory::CUSTOM,
            function () {
                usleep(500); // 0.5ms - State validation
            }
        );
    },
    ['component' => 'counter', 'action' => 'increment']
);

echo "\nAction Execution Timeline:\n";
$timeline = $tracker->generateTimeline();

foreach ($timeline as $event) {
    $indent = str_repeat('  ', $event['depth']);
    echo sprintf(
        "  %s[%s] %s (%.2fms)\n",
        $indent,
        $event['category'],
        $event['name'],
        $event['duration_ms']
    );
}

echo "\n" . str_repeat('=', 50) . "\n\n";

// Example 2: Action Metrics Analysis
echo "Example 2: Action Metrics Analysis\n";
echo str_repeat('-', 50) . "\n";

// Simuliere mehrere Action Executions
for ($i = 0; $i < 3; $i++) {
    $profiler->profileCsrfValidation($componentId, 'increment', fn() => usleep(200));
    $profiler->profileAuthorizationCheck($componentId, 'increment', fn() => usleep(300));
    $profiler->profileParameterBinding($componentId, 'increment', fn() => usleep(400));

    $tracker->measure(
        "livecomponent.counter.increment",
        \App\Framework\Performance\PerformanceCategory::CUSTOM,
        function () use ($tracker) {
            $tracker->measure("livecomponent.action.execute", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(2000));
            $tracker->measure("livecomponent.state.validate", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(500));
        },
        ['component' => 'counter', 'action' => 'increment']
    );
}

$metrics = $profiler->getActionMetrics('counter', 'increment');

echo "\nAction Metrics for counter.increment:\n";
echo "  Executions: {$metrics['executions']}\n";
echo "  Total Time: " . number_format($metrics['total_time_ms'], 2) . "ms\n";
echo "  Avg Time per Execution: " . number_format($metrics['avg_time_per_execution_ms'], 2) . "ms\n";
echo "\n  Phase Timings:\n";

foreach ($metrics['phase_timings'] as $phase => $timing) {
    echo sprintf(
        "    • %s: %.2fms avg (%d calls)\n",
        $phase,
        $timing['avg_ms'],
        $timing['count']
    );
}

echo "\n" . str_repeat('=', 50) . "\n\n";

// Example 3: Component Summary
echo "Example 3: Component Performance Summary\n";
echo str_repeat('-', 50) . "\n";

$tracker->reset();

// Simuliere verschiedene Operations für mehrere Components
$components = ['counter', 'search', 'user-card'];
$actions = ['increment', 'updateQuery', 'refresh'];

foreach ($components as $index => $componentName) {
    $compId = ComponentId::create($componentName, "instance-{$index}");
    $action = $actions[$index];

    // Simuliere 2-3 Action executions
    for ($i = 0; $i < rand(2, 3); $i++) {
        $profiler->profileCsrfValidation($compId, $action, fn() => usleep(rand(150, 250)));
        $profiler->profileAuthorizationCheck($compId, $action, fn() => usleep(rand(250, 350)));

        $tracker->measure(
            "livecomponent.{$componentName}.{$action}",
            \App\Framework\Performance\PerformanceCategory::CUSTOM,
            function () use ($tracker) {
                $tracker->measure("livecomponent.action.execute", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(rand(1500, 2500)));
            },
            ['component' => $componentName, 'action' => $action]
        );
    }
}

echo "\nComponent Performance Summaries:\n\n";

foreach ($components as $componentName) {
    $summary = $profiler->getComponentSummary($componentName);

    echo "  {$summary['component']}:\n";
    echo "    Total Operations: {$summary['total_operations']}\n";
    echo "    Total Time: " . number_format($summary['total_time_ms'], 2) . "ms\n";
    echo "    Operations:\n";

    foreach ($summary['operations'] as $opName => $stats) {
        echo sprintf(
            "      • %s: %.2fms avg (min: %.2fms, max: %.2fms, count: %d)\n",
            basename($opName),
            $stats['avg_time_ms'],
            $stats['min_time_ms'],
            $stats['max_time_ms'],
            $stats['count']
        );
    }

    echo "\n";
}

echo str_repeat('=', 50) . "\n\n";

// Example 4: System-Wide Performance Report
echo "Example 4: System-Wide Performance Report\n";
echo str_repeat('-', 50) . "\n";

$report = $profiler->generatePerformanceReport();

echo "\nSystem-Wide Performance Report\n";
echo "  Generated at: {$report['generated_at']}\n";
echo "  Total Components: {$report['total_components']}\n";
echo "  Total Operations: {$report['total_operations']}\n\n";

echo "  Component Breakdown:\n";

foreach ($report['components'] as $componentName => $data) {
    echo "    {$componentName}:\n";
    echo "      Operations: {$data['operations']}\n";
    echo "      Total Time: " . number_format($data['total_time_ms'], 2) . "ms\n";
    echo "      Actions: " . implode(', ', array_keys($data['actions'])) . "\n";
    echo "\n";
}

echo str_repeat('=', 50) . "\n\n";

// Example 5: Profiling mit Idempotency
echo "Example 5: Idempotency Profiling\n";
echo str_repeat('-', 50) . "\n";

$tracker->reset();

$componentId = ComponentId::create('payment', 'order-456');

// Erste Ausführung - kein Cache
$profiler->profileIdempotencyCheck(
    $componentId,
    'processPayment',
    function () {
        usleep(500); // 0.5ms - Check cache, not found
        return null;
    }
);

$tracker->measure(
    "livecomponent.payment.processPayment",
    \App\Framework\Performance\PerformanceCategory::CUSTOM,
    function () use ($tracker) {
        $tracker->measure("livecomponent.action.execute", \App\Framework\Performance\PerformanceCategory::CUSTOM, fn() => usleep(5000)); // 5ms - Actual processing
    },
    ['component' => 'payment', 'action' => 'processPayment']
);

// Zweite Ausführung - Cache Hit
$profiler->profileIdempotencyCheck(
    $componentId,
    'processPayment',
    function () {
        usleep(200); // 0.2ms - Cache hit, return cached result
        return ['cached' => true];
    }
);

echo "\nIdempotency Profiling Timeline:\n";
$idempotencyTimeline = $tracker->generateTimeline();

foreach ($idempotencyTimeline as $event) {
    $indent = str_repeat('  ', $event['depth']);
    echo sprintf(
        "  %s[%s] %s (%.2fms)\n",
        $indent,
        $event['category'],
        $event['name'],
        $event['duration_ms']
    );
}

echo "\n  💡 Cache hit reduced execution from 5.5ms to 0.2ms (96% faster)\n";

echo "\n" . str_repeat('=', 50) . "\n\n";

// Summary
echo "✅ Action Profiling Examples completed!\n\n";

echo "Key Insights:\n";
echo "  • Security checks (CSRF, Auth, Rate Limit) add ~0.5-0.7ms overhead\n";
echo "  • Parameter binding with reflection typically ~0.4ms\n";
echo "  • Action execution is the main bottleneck (varies by business logic)\n";
echo "  • Idempotency caching can provide 90%+ performance improvement\n";
echo "  • ActionProfiler provides detailed metrics for optimization\n\n";

echo "Use Cases:\n";
echo "  1. Identify slow security checks\n";
echo "  2. Optimize parameter binding for complex DTOs\n";
echo "  3. Monitor action execution performance over time\n";
echo "  4. Validate idempotency cache effectiveness\n";
echo "  5. Generate system-wide performance reports\n\n";

echo "Next Steps:\n";
echo "  1. Integrate ActionProfiler into production monitoring\n";
echo "  2. Set performance budgets for each action phase\n";
echo "  3. Alert on performance degradation\n";
echo "  4. Use metrics for optimization priority\n\n";
