<?php

declare(strict_types=1);

/**
 * Test script for the Discovery Event System
 */

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

use App\Framework\Cache\Driver\InMemoryCache;
use App\Framework\Cache\GeneralCache;
use App\Framework\Core\Events\EventDispatcher;
use App\Framework\Core\PathProvider;
use App\Framework\DateTime\SystemClock;
use App\Framework\DI\DefaultContainer;
use App\Framework\Discovery\Events\EventAggregator;
use App\Framework\Discovery\Factory\DiscoveryServiceFactory;
use App\Framework\Discovery\ValueObjects\DiscoveryConfiguration;
use App\Framework\Discovery\ValueObjects\DiscoveryOptions;
use App\Framework\Discovery\ValueObjects\ScanType;
use App\Framework\Filesystem\FileSystemService;
use App\Framework\Logging\DefaultLogger;
use App\Framework\Logging\Handlers\ConsoleHandler;
use App\Framework\Logging\LogLevel;
use App\Framework\Performance\MemoryMonitor;
use App\Framework\Reflection\CachedReflectionProvider;
use App\Framework\Serializer\Php\PhpSerializer;

echo "🎯 Testing Discovery Event System\n";
echo "================================\n";

try {
    // Setup basic dependencies
    $pathProvider = new PathProvider(__DIR__ . '/../..');
    $cacheDriver = new InMemoryCache();
    $serializer = new PhpSerializer();
    $cache = new GeneralCache($cacheDriver, $serializer);
    $clock = new SystemClock();
    $container = new DefaultContainer();

    // Create event dispatcher
    $eventDispatcher = new EventDispatcher();

    // Optional dependencies for testing
    $consoleHandler = new ConsoleHandler();
    $logger = new DefaultLogger(LogLevel::INFO, [$consoleHandler]);
    $memoryMonitor = new MemoryMonitor();
    $reflectionProvider = new CachedReflectionProvider();
    $fileSystemService = new FileSystemService();

    // Register optional services in container
    $container->singleton(\App\Framework\Logging\Logger::class, $logger);
    $container->singleton(\App\Framework\Performance\MemoryMonitor::class, $memoryMonitor);
    $container->singleton(\App\Framework\Reflection\ReflectionProvider::class, $reflectionProvider);
    $container->singleton(\App\Framework\Filesystem\FileSystemService::class, $fileSystemService);
    $container->singleton(\App\Framework\Core\Events\EventDispatcher::class, $eventDispatcher);

    echo "✅ Dependencies initialized\n";

    // Test 1: Event Aggregator Setup
    echo "\n🧪 Test 1: Event Aggregator Setup\n";

    $eventAggregator = new EventAggregator($eventDispatcher, $clock, $logger);
    echo "✅ Event Aggregator created and handlers registered\n";

    $initialStats = $eventAggregator->getStatistics();
    echo "  Initial Statistics: " . json_encode($initialStats) . "\n";

    // Test 2: Discovery Service with Event Integration
    echo "\n🧪 Test 2: Discovery Service with Event Integration\n";

    // Create factory
    $factory = new DiscoveryServiceFactory($container, $pathProvider, $cache, $clock);

    // Create configuration with aggressive memory constraints to trigger events
    $config = new DiscoveryConfiguration(
        paths: [$pathProvider->getBasePath() . '/src/Application/Admin'],
        useCache: false,
        enableEventDispatcher: true,
        enableMemoryMonitoring: true,
        enablePerformanceTracking: true,
        memoryLimitMB: 16, // Very low limit to trigger memory events
        maxFilesPerBatch: 5, // Small batches to trigger chunk events
        memoryPressureThreshold: 0.5 // Lower threshold for more events
    );

    // Create service with full event integration
    $discoveryService = $factory->create($config);
    echo "✅ Discovery service created with event integration\n";

    // Test 3: Run Discovery to Generate Events
    echo "\n🧪 Test 3: Running Discovery to Generate Events\n";

    $startTime = microtime(true);
    $startMemory = memory_get_usage(true);

    $options = new DiscoveryOptions(
        scanType: ScanType::FULL,
        paths: [$pathProvider->getBasePath() . '/src/Application/Admin'],
        useCache: false
    );

    echo "Starting discovery process...\n";
    $registry = $discoveryService->discoverWithOptions($options);

    $endTime = microtime(true);
    $endMemory = memory_get_usage(true);

    echo "✅ Discovery completed\n";
    echo "  Processing Time: " . round(($endTime - $startTime) * 1000, 2) . "ms\n";
    echo "  Memory Used: " . round(($endMemory - $startMemory) / 1024 / 1024, 2) . "MB\n";
    echo "  Registry Size: " . count($registry) . " items\n";

    // Test 4: Event Statistics Analysis
    echo "\n🧪 Test 4: Event Statistics Analysis\n";

    $finalStats = $eventAggregator->getStatistics();
    echo "✅ Final Event Statistics:\n";
    foreach ($finalStats as $key => $value) {
        echo "  {$key}: {$value}\n";
    }

    // Test 5: Comprehensive Analytics
    echo "\n🧪 Test 5: Comprehensive Event Analytics\n";

    $analytics = $eventAggregator->getDiscoveryAnalytics();
    echo "✅ Discovery Analytics generated\n";

    // Memory Pressure Analysis
    if (! empty($analytics['memory_pressure'])) {
        echo "\n📊 Memory Pressure Analysis:\n";
        $memoryAnalysis = $analytics['memory_pressure'];
        echo "  Total Events: {$memoryAnalysis['total_events']}\n";
        echo "  Critical Events: {$memoryAnalysis['critical_events']}\n";
        echo "  Warning Events: {$memoryAnalysis['warning_events']}\n";
        echo "  Average Pressure: " . round($memoryAnalysis['average_pressure'] * 100, 1) . "%\n";

        if (! empty($memoryAnalysis['pressure_spikes'])) {
            echo "  Pressure Spikes: " . count($memoryAnalysis['pressure_spikes']) . "\n";
        }
    } else {
        echo "  No memory pressure events detected\n";
    }

    // Cleanup Effectiveness Analysis
    if (! empty($analytics['cleanup_effectiveness'])) {
        echo "\n📊 Cleanup Effectiveness Analysis:\n";
        $cleanupAnalysis = $analytics['cleanup_effectiveness'];
        echo "  Total Cleanups: {$cleanupAnalysis['total_cleanups']}\n";
        echo "  Effective Cleanups: {$cleanupAnalysis['effective_cleanups']}\n";
        echo "  Emergency Cleanups: {$cleanupAnalysis['emergency_cleanups']}\n";
        echo "  Effectiveness Ratio: " . round($cleanupAnalysis['effectiveness_ratio'] * 100, 1) . "%\n";
        echo "  Total Memory Freed: {$cleanupAnalysis['total_memory_freed']}\n";
    } else {
        echo "  No cleanup events detected\n";
    }

    // Memory Leak Analysis
    if (! empty($analytics['memory_leaks'])) {
        echo "\n📊 Memory Leak Analysis:\n";
        $leakAnalysis = $analytics['memory_leaks'];
        echo "  Leaks Detected: {$leakAnalysis['total_leaks_detected']}\n";
        echo "  Severity Distribution:\n";
        foreach ($leakAnalysis['severity_distribution'] as $severity => $count) {
            echo "    {$severity}: {$count}\n";
        }

        if (! empty($leakAnalysis['critical_leaks'])) {
            echo "  Critical Leaks: " . count($leakAnalysis['critical_leaks']) . "\n";
        }
    } else {
        echo "  No memory leaks detected\n";
    }

    // Chunk Performance Analysis
    if (! empty($analytics['chunk_performance'])) {
        echo "\n📊 Chunk Performance Analysis:\n";
        $chunkAnalysis = $analytics['chunk_performance'];
        echo "  Total Chunk Events: {$chunkAnalysis['total_chunk_events']}\n";
        echo "  Completed Chunks: {$chunkAnalysis['completed_chunks']}\n";
        echo "  Failed Chunks: {$chunkAnalysis['failed_chunks']}\n";
        echo "  Memory Adjustments: {$chunkAnalysis['memory_adjustments']}\n";
        echo "  Average Chunk Size: " . round($chunkAnalysis['average_chunk_size'], 1) . "\n";
        echo "  Average Processing Time: " . round($chunkAnalysis['average_processing_time'], 3) . "s\n";
        echo "  Success Rate: " . round($chunkAnalysis['success_rate'] * 100, 1) . "%\n";
        echo "  Total Memory Usage: {$chunkAnalysis['total_memory_usage']}\n";

        echo "  Event Type Distribution:\n";
        foreach ($chunkAnalysis['event_type_distribution'] as $type => $count) {
            echo "    {$type}: {$count}\n";
        }
    } else {
        echo "  No chunk processing events detected\n";
    }

    // Strategy Change Analysis
    if (! empty($analytics['strategy_changes'])) {
        echo "\n📊 Strategy Change Analysis:\n";
        $strategyAnalysis = $analytics['strategy_changes'];
        echo "  Total Strategy Changes: {$strategyAnalysis['total_strategy_changes']}\n";
        echo "  Emergency Changes: {$strategyAnalysis['emergency_changes']}\n";
        echo "  Strategy Downgrades: {$strategyAnalysis['strategy_downgrades']}\n";
        echo "  Emergency Ratio: " . round($strategyAnalysis['emergency_ratio'] * 100, 1) . "%\n";

        echo "  Strategy Usage:\n";
        foreach ($strategyAnalysis['strategy_usage'] as $strategy => $count) {
            echo "    {$strategy}: {$count}\n";
        }
    } else {
        echo "  No strategy changes detected\n";
    }

    // Test 6: Event Pattern Recognition
    echo "\n🧪 Test 6: Event Pattern Recognition\n";

    // Analyze event patterns over time
    $totalEvents = $finalStats['total_events'];
    if ($totalEvents > 0) {
        echo "✅ Event Pattern Analysis:\n";

        $memoryEventRatio = round($finalStats['memory_pressure_events'] / $totalEvents * 100, 1);
        $cleanupEventRatio = round($finalStats['cleanup_events'] / $totalEvents * 100, 1);
        $chunkEventRatio = round($finalStats['chunk_events'] / $totalEvents * 100, 1);

        echo "  Memory Pressure Events: {$memoryEventRatio}% of all events\n";
        echo "  Cleanup Events: {$cleanupEventRatio}% of all events\n";
        echo "  Chunk Processing Events: {$chunkEventRatio}% of all events\n";

        // Event intensity analysis
        $discoveryDuration = $endTime - $startTime;
        $eventsPerSecond = round($totalEvents / $discoveryDuration, 2);
        echo "  Event Intensity: {$eventsPerSecond} events/second\n";

        // Memory efficiency analysis
        if (! empty($analytics['memory_pressure']) && ! empty($analytics['cleanup_effectiveness'])) {
            $memoryEvents = $analytics['memory_pressure']['total_events'];
            $cleanupEvents = $analytics['cleanup_effectiveness']['total_cleanups'];

            if ($memoryEvents > 0) {
                $cleanupResponseRatio = round($cleanupEvents / $memoryEvents, 2);
                echo "  Cleanup Response Ratio: {$cleanupResponseRatio} cleanups per memory pressure event\n";
            }
        }
    } else {
        echo "  No events generated during discovery\n";
    }

    // Test 7: Health Status with Event Information
    echo "\n🧪 Test 7: Health Status with Event Information\n";

    $healthStatus = $discoveryService->getHealthStatus();
    echo "✅ Health Status Retrieved:\n";
    echo "  Service Status: {$healthStatus['service']}\n";

    if (isset($healthStatus['memory_management'])) {
        echo "  Memory Status: {$healthStatus['memory_management']['status']}\n";
        echo "  Memory Usage: {$healthStatus['memory_management']['current_usage']}\n";
        echo "  Memory Strategy: {$healthStatus['memory_management']['strategy']}\n";
        echo "  Guard Checks: {$healthStatus['memory_management']['guard_checks']}\n";
        echo "  Emergency Mode: " . ($healthStatus['memory_management']['emergency_mode'] ? 'ON' : 'OFF') . "\n";
    }

    echo "\n🎉 All event system tests completed successfully!\n";
    echo "\n🏆 Key Event System Features Verified:\n";
    echo "  ✅ Memory pressure event detection and emission\n";
    echo "  ✅ Memory cleanup event tracking with effectiveness metrics\n";
    echo "  ✅ Memory leak detection with severity classification\n";
    echo "  ✅ Chunk processing events with performance metrics\n";
    echo "  ✅ Memory strategy change events with impact analysis\n";
    echo "  ✅ Event aggregation and comprehensive analytics\n";
    echo "  ✅ Real-time event statistics and monitoring\n";
    echo "  ✅ Event pattern recognition and trend analysis\n";
    echo "  ✅ Full Discovery service integration with events\n";
    echo "  ✅ Health status reporting with event-based insights\n";

} catch (Throwable $e) {
    echo "\n❌ Error during event system testing:\n";
    echo "  Message: " . $e->getMessage() . "\n";
    echo "  File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "  Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}
