<?php

declare(strict_types=1);

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

use App\Framework\DI\InitializerDependencyGraph;
use App\Framework\Reflection\CachedReflectionProvider;

echo "=== Testing InitializerDependencyGraph API ===\n\n";

try {
    $reflectionProvider = new CachedReflectionProvider();
    $graph = new InitializerDependencyGraph($reflectionProvider);

    // Add some test initializers
    $graph->addInitializer('App\\Cache\\Cache', 'App\\Config\\CacheInitializer', 'createCache');
    $graph->addInitializer('App\\Database\\Connection', 'App\\Config\\DatabaseInitializer', 'createConnection');
    $graph->addInitializer('App\\Logging\\Logger', 'App\\Config\\LoggerInitializer', 'createLogger');

    echo "=== Testing New API Methods ===\n";

    // Test hasNode
    echo "Has Cache node: " . ($graph->hasNode('App\\Cache\\Cache') ? 'Yes' : 'No') . "\n";
    echo "Has Redis node: " . ($graph->hasNode('App\\Cache\\Redis') ? 'Yes' : 'No') . "\n\n";

    // Test getNode
    $cacheNode = $graph->getNode('App\\Cache\\Cache');
    if ($cacheNode) {
        echo "✅ Cache node found:\n";
        echo "   " . $cacheNode->toString() . "\n";
        echo "   Class: " . $cacheNode->getClassName() . "\n";
        echo "   Method: " . $cacheNode->getMethodName() . "\n";
        echo "   Dependencies: " . count($cacheNode->dependencies) . "\n\n";
    }

    $missingNode = $graph->getNode('App\\NonExistent\\Service');
    echo "Missing node result: " . ($missingNode === null ? 'null (correct)' : 'found (unexpected)') . "\n\n";

    // Test getNodes (new API)
    echo "=== Testing Node Enumeration ===\n";
    $nodes = $graph->getNodes();
    echo "Total nodes: " . count($nodes) . "\n";

    foreach ($nodes as $returnType => $node) {
        echo "- $returnType: {$node->getClassName()}::{$node->getMethodName()}\n";
    }

    echo "\n=== Testing Execution Order ===\n";
    $executionOrder = $graph->getExecutionOrder();
    echo "Execution order: " . implode(' → ', $executionOrder) . "\n\n";

    // Test backward compatibility
    echo "=== Testing Backward Compatibility ===\n";
    $nodesArray = $graph->getNodesAsArray();
    echo "Nodes as array format (backward compatibility):\n";
    foreach ($nodesArray as $returnType => $nodeData) {
        echo "- $returnType: {$nodeData['class']}::{$nodeData['method']} (deps: " . count($nodeData['dependencies']) . ")\n";
    }

    echo "\n✅ All InitializerDependencyGraph API tests passed!\n";

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