<?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\Core\PathProvider;
use App\Framework\DateTime\SystemClock;
use App\Framework\DI\DefaultContainer;
use App\Framework\DI\InitializerMapper;
use App\Framework\Discovery\UnifiedDiscoveryService;
use App\Framework\Discovery\ValueObjects\DiscoveryConfiguration;
use App\Framework\Filesystem\FileSystemService;
use App\Framework\Reflection\CachedReflectionProvider;
use App\Framework\Serializer\Json\JsonSerializer;
use Tests\Debug\DebugInitializer;

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

// Clear previous log
$logFile = __DIR__ . '/initializer-execution.log';
if (file_exists($logFile)) {
    unlink($logFile);
}

try {
    // Setup
    $projectRoot = dirname(__DIR__, 2);
    $container = new DefaultContainer();
    $pathProvider = new PathProvider($projectRoot);
    $clock = new SystemClock();
    $fileSystemService = new FileSystemService();
    $reflectionProvider = new CachedReflectionProvider();

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

    // Create InitializerMapper
    $initializerMapper = new InitializerMapper();

    // Configure discovery to scan the tests/debug directory
    $debugPath = __DIR__;
    $config = new DiscoveryConfiguration(
        paths: [$debugPath],
        attributeMappers: [$initializerMapper],
        targetInterfaces: [],
        useCache: false
    );

    // Create discovery service
    $discoveryService = new UnifiedDiscoveryService(
        pathProvider: $pathProvider,
        cache: $cache,
        clock: $clock,
        reflectionProvider: $reflectionProvider,
        configuration: $config,
        attributeMappers: [$initializerMapper],
        targetInterfaces: []
    );

    echo "Scanning for debug initializers...\n";

    $registry = $discoveryService->discover();

    echo "Discovery completed!\n\n";

    // Check if our debug initializer was found
    $initializerResults = $registry->attributes->get('App\\Framework\\DI\\Initializer');

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

    if (! empty($initializerResults)) {
        foreach ($initializerResults as $mapping) {
            $className = $mapping->class->getFullyQualified();
            $methodName = $mapping->method ? $mapping->method->toString() : '(class-level)';
            echo "- {$className}::{$methodName}\n";

            if ($mapping->mappedData) {
                echo "  Return Type: " . ($mapping->mappedData['return'] ?? 'null') . "\n";
            }
        }
    }

    echo "\n=== Manual Execution Test ===\n";

    // Now manually execute the debug initializer to see if it works
    $container->instance(\App\Framework\DI\Container::class, $container);

    echo "Creating DebugInitializer...\n";
    $debugInitializer = new DebugInitializer($container);

    echo "Executing void method...\n";
    $debugInitializer->debugTest();

    echo "Executing service method...\n";
    $service = $debugInitializer->debugService();
    echo "Service created: " . json_encode($service) . "\n\n";

    // Check if log file was created
    if (file_exists($logFile)) {
        echo "=== Execution Log ===\n";
        echo file_get_contents($logFile);
    } else {
        echo "❌ No execution log found\n";
    }

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