<?php

declare(strict_types=1);

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

use App\Framework\Core\AppBootstrapper;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Mcp\Tools\FrameworkInitializerAgent;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\Performance\MemoryMonitor;

echo "🔧 Testing Framework Initializer Agent\n";
echo "=====================================\n\n";

try {
    // Bootstrap framework
    $clock = new SystemClock();
    $highResClock = new SystemHighResolutionClock();
    $memoryMonitor = new MemoryMonitor();
    $collector = new EnhancedPerformanceCollector($clock, $highResClock, $memoryMonitor, enabled: false);

    $bootstrapper = new AppBootstrapper(__DIR__ . '/../..', $collector, $memoryMonitor);
    $container = $bootstrapper->bootstrapWorker();

    $initializerAgent = $container->get(FrameworkInitializerAgent::class);

    echo "✅ Framework bootstrapped successfully\n";
    echo "✅ Initializer Agent retrieved\n\n";

    // Test 1: Analyze All Initializers
    echo "📋 Test 1: Analyze All Initializers\n";
    echo "---------------------------------\n";

    $analysis = $initializerAgent->analyzeAllInitializers();

    echo "📊 Analysis Results:\n";
    echo "  Total Initializers: " . $analysis['total_initializers'] . "\n";
    echo "  Total Files: " . $analysis['total_files'] . "\n";
    echo "  Health Status: " . $analysis['health_status'] . "\n";
    echo "  Categories Found: " . count($analysis['categories']) . "\n";

    echo "\n📦 Categories:\n";
    foreach ($analysis['categories'] as $category => $initializers) {
        echo "  • {$category}: " . count($initializers) . " initializers\n";
    }
    echo "\n";

    // Test 2: Initializer Dependencies
    echo "📋 Test 2: Initializer Dependencies\n";
    echo "----------------------------------\n";

    $dependencies = $initializerAgent->analyzeInitializerDependencies();

    echo "🔗 Dependency Analysis:\n";
    echo "  Dependencies Mapped: " . count($dependencies['dependency_map']) . "\n";
    echo "  Circular Dependencies: " . count($dependencies['circular_dependencies']) . "\n";
    echo "  Initialization Order: " . count($dependencies['initialization_order']) . "\n";
    echo "  Orphaned Initializers: " . count($dependencies['orphaned_initializers']) . "\n";
    echo "\n";

    // Test 3: Health Check
    echo "📋 Test 3: Initializer Health Check\n";
    echo "----------------------------------\n";

    $health = $initializerAgent->checkInitializerHealth();

    echo "🏥 Health Check Results:\n";
    echo "  Overall Health: " . $health['overall_health'] . "\n";
    echo "  Total Checked: " . $health['total_checked'] . "\n";
    echo "  Healthy: " . $health['healthy_count'] . "\n";
    echo "  Warnings: " . $health['warning_count'] . "\n";
    echo "  Unhealthy: " . $health['unhealthy_count'] . "\n";
    echo "\n";

    // Test 4: Performance Analysis
    echo "📋 Test 4: Performance Analysis\n";
    echo "-----------------------------\n";

    $performance = $initializerAgent->analyzeInitializerPerformance();

    echo "⚡ Performance Results:\n";
    echo "  Total Initializers: " . $performance['total_initializers'] . "\n";
    echo "  Average Complexity: " . $performance['average_complexity'] . "\n";
    echo "  Most Complex: " . (empty($performance['most_complex']) ? 'None' : count($performance['most_complex'])) . "\n";
    echo "  Bottlenecks: " . count($performance['performance_bottlenecks']) . "\n";
    echo "  Optimization Opportunities: " . count($performance['optimization_opportunities']) . "\n";
    echo "\n";

    // Test 5: Category Analysis
    echo "📋 Test 5: Category Analysis\n";
    echo "---------------------------\n";

    $categories = $initializerAgent->analyzeInitializersByCategory();

    echo "📂 Category Analysis:\n";
    echo "  Total Categories: " . $categories['total_categories'] . "\n";
    echo "\n📊 Category Details:\n";
    foreach ($categories['category_analysis'] as $category => $analysis) {
        echo "  • {$category}:\n";
        echo "    - Count: " . $analysis['count'] . "\n";
        echo "    - Health: " . $analysis['health_status'] . "\n";
        echo "    - Avg Complexity: " . $analysis['complexity_average'] . "\n";
    }
    echo "\n";

    // Test 6: Bootstrap Test
    echo "📋 Test 6: Bootstrap Test\n";
    echo "------------------------\n";

    $bootstrap = $initializerAgent->testInitializerBootstrap();

    echo "🚀 Bootstrap Test Results:\n";
    echo "  Overall Status: " . $bootstrap['overall_status'] . "\n";
    echo "  Total Time: " . $bootstrap['total_time_ms'] . "ms\n";
    echo "  Performance: " . $bootstrap['performance_assessment']['assessment'] . "\n";

    if (isset($bootstrap['test_results']['discovery'])) {
        echo "  Discovery: " . $bootstrap['test_results']['discovery']['status'] .
             " (" . $bootstrap['test_results']['discovery']['time_ms'] . "ms)\n";
    }
    if (isset($bootstrap['test_results']['class_loading'])) {
        echo "  Class Loading: " . $bootstrap['test_results']['class_loading']['status'] .
             " (" . $bootstrap['test_results']['class_loading']['time_ms'] . "ms)\n";
    }
    if (isset($bootstrap['test_results']['dependency_resolution'])) {
        echo "  Dependencies: " . $bootstrap['test_results']['dependency_resolution']['status'] .
             " (" . $bootstrap['test_results']['dependency_resolution']['time_ms'] . "ms)\n";
    }

    if (! empty($bootstrap['errors'])) {
        echo "\n❌ Errors:\n";
        foreach ($bootstrap['errors'] as $error) {
            echo "  • " . $error['stage'] . ": " . $error['error'] . "\n";
        }
    }
    echo "\n";

    echo "🎯 Framework Initializer Agent Test Summary:\n";
    echo "==========================================\n";
    echo "✅ All Initializers Analysis: Working\n";
    echo "✅ Dependency Analysis: Working\n";
    echo "✅ Health Checks: Working\n";
    echo "✅ Performance Analysis: Working\n";
    echo "✅ Category Analysis: Working\n";
    echo "✅ Bootstrap Testing: Working\n";
    echo "\n";
    echo "🚀 Framework Initializer Agent is fully operational!\n";
    echo "📊 Discovered " . ($analysis['total_initializers'] ?? 0) . " initializers across " . count($analysis['categories'] ?? []) . " categories!\n";

} catch (Exception $e) {
    echo "❌ Framework Initializer Agent test failed: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    exit(1);
}

echo "\n🎯 Framework Initializer Agent test completed successfully!\n";
