<?php

declare(strict_types=1);

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

use App\Framework\Console\ConsoleCommandMapper;
use App\Framework\Core\ValueObjects\ClassName;
use App\Framework\Discovery\ValueObjects\FileContext;
use App\Framework\Discovery\Visitors\AttributeVisitor;
use App\Framework\Filesystem\File;
use App\Framework\Filesystem\FileMetadata;
use App\Framework\Filesystem\ValueObjects\FilePath;

// Create a custom AttributeVisitor with debug output
class DebugAttributeVisitor extends AttributeVisitor
{
    public function visitClass(ClassName $className, FileContext $context): void
    {
        echo "🔍 visitClass called for: " . $className->getFullyQualified() . PHP_EOL;

        if (! $className->exists()) {
            echo "❌ Class does not exist!" . PHP_EOL;

            return;
        }

        echo "✅ Class exists, proceeding with reflection" . PHP_EOL;

        try {
            parent::visitClass($className, $context);

            // Check what was discovered
            $registry = $this->getRegistry();
            $total = $registry->count();
            echo "✅ visitClass completed. Total attributes discovered: $total" . PHP_EOL;

            $consoleCommands = $registry->get('App\\Framework\\Console\\ConsoleCommand');
            echo "ConsoleCommand attributes in registry: " . count($consoleCommands) . PHP_EOL;

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

echo "=== Debug Visitor Process ===" . PHP_EOL;

// Create the debug attribute visitor
$visitor = new DebugAttributeVisitor([
    new ConsoleCommandMapper(),
]);

echo "✅ DebugAttributeVisitor created" . PHP_EOL;

// Test with the MCP Server Command class
$className = ClassName::create('App\\Framework\\Mcp\\Console\\McpServerCommand');
$filePathStr = __DIR__ . '/../../src/Framework/Mcp/Console/McpServerCommand.php';
$filePath = FilePath::create($filePathStr);

// Create file metadata
$stat = stat($filePathStr);
$metadata = new FileMetadata(
    path: $filePath,
    size: $stat['size'] ?? 0,
    lastModified: $stat['mtime'] ?? time()
);

$file = new File($filePath, $metadata);
$context = new FileContext($file, $filePath);

echo "Calling visitClass..." . PHP_EOL;

// Visit the class to discover attributes
$visitor->visitClass($className, $context);

// Final check
$registry = $visitor->getRegistry();
echo PHP_EOL . "Final results:" . PHP_EOL;
echo "Total attributes: " . $registry->count() . PHP_EOL;
echo "Attribute types: " . count($registry->getAllTypes()) . PHP_EOL;

foreach ($registry->getAllTypes() as $type) {
    $count = $registry->getCount($type);
    echo "  - $type: $count" . PHP_EOL;
}
