<?php

declare(strict_types=1);

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

use App\Framework\Cache\Driver\InMemoryCache;
use App\Framework\Cache\GeneralCache;
use App\Framework\Context\ExecutionContext;
use App\Framework\Core\PathProvider;
use App\Framework\DateTime\SystemClock;
use App\Framework\DI\DefaultContainer;
use App\Framework\Discovery\DiscoveryServiceBootstrapper;
use App\Framework\Reflection\CachedReflectionProvider;
use App\Framework\Serializer\Json\JsonSerializer;

echo "=== Testing Initializer Execution ===\n\n";

try {
    // Setup with correct path
    $projectRoot = dirname(__DIR__, 2);

    echo "Project root: $projectRoot\n";

    $container = new DefaultContainer();
    $pathProvider = new PathProvider($projectRoot);
    $clock = new SystemClock();

    // Create cache for discovery
    $cacheDriver = new InMemoryCache();
    $serializer = new JsonSerializer();
    $cache = new GeneralCache($cacheDriver, $serializer);

    // Register required dependencies
    $container->instance(PathProvider::class, $pathProvider);
    $container->instance(\App\Framework\Cache\CacheDriver::class, $cacheDriver);
    $container->instance(\App\Framework\Serializer\Serializer::class, $serializer);
    $container->instance(\App\Framework\Cache\Cache::class, $cache);
    $container->instance(\App\Framework\DateTime\Clock::class, $clock);
    $container->instance(\App\Framework\Reflection\ReflectionProvider::class, new CachedReflectionProvider());

    echo "Current execution context: " . ExecutionContext::detect()->getType()->value . "\n\n";

    // Create bootstrapper
    $bootstrapper = new DiscoveryServiceBootstrapper($container, $clock);

    echo "Starting bootstrap process...\n";

    // This should discover AND execute initializers
    $registry = $bootstrapper->bootstrap();

    echo "\nBootstrap completed!\n\n";

    echo "=== Registry Results ===\n";
    echo "Total registry count: " . count($registry) . "\n";
    echo "Attributes registry count: " . count($registry->attributes) . "\n\n";

    // Check what initializers were found
    $initializerAttributeClass = 'App\\Framework\\DI\\Initializer';
    $initializers = $registry->attributes->get($initializerAttributeClass);

    echo "=== Initializer Results ===\n";
    echo "Initializers found: " . count($initializers) . "\n\n";

    if (! empty($initializers)) {
        echo "✅ Found initializers:\n";
        foreach (array_slice($initializers, 0, 5) as $mapping) {
            $className = $mapping->class->getFullyQualified();
            $methodName = $mapping->method ? $mapping->method->toString() : '(class-level)';
            echo "- {$className}::{$methodName}\n";
            echo "  Target: " . $mapping->target . "\n";

            // Check the mapped data structure
            if ($mapping->mappedData) {
                echo "  Mapped Data Keys: " . implode(', ', array_keys($mapping->mappedData)) . "\n";
                if (isset($mapping->mappedData['return'])) {
                    echo "  Return Type: " . ($mapping->mappedData['return'] ?? 'null') . "\n";
                }
                if (isset($mapping->mappedData['contexts'])) {
                    echo "  Contexts: " . json_encode($mapping->mappedData['contexts']) . "\n";
                }
            }
            echo "\n";
        }
    }

    // Check what's in the container now
    echo "=== Container Status ===\n";

    // Check if some key services were registered
    $expectedServices = [
        'App\\Framework\\Cache\\Cache',
        'App\\Framework\\Logging\\Logger',
        'App\\Framework\\Database\\EntityManager',
        'App\\Framework\\Http\\Session\\SessionManager',
        'App\\Framework\\View\\TemplateRenderer',
        'App\\Framework\\Performance\\PerformanceCollectorInterface',
        'App\\Framework\\Discovery\\Results\\DiscoveryRegistry',
    ];

    foreach ($expectedServices as $service) {
        $exists = $container->has($service);
        echo "- $service: " . ($exists ? "✅ Registered" : "❌ Missing") . "\n";
    }

} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}
