<?php

declare(strict_types=1);

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

use App\Framework\LiveComponents\Attributes\DataProvider;

echo "\nManual DataProvider Attribute Scan\n";
echo str_repeat('=', 70) . "\n\n";

// Manuell scannen für DataProvider Attribute
$searchPath = __DIR__ . '/../../src/Application/LiveComponents/Services';

echo "Scanning path: {$searchPath}\n\n";

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($searchPath, RecursiveDirectoryIterator::SKIP_DOTS)
);

$foundClasses = [];

foreach ($iterator as $file) {
    if ($file->getExtension() !== 'php') {
        continue;
    }

    $filePath = $file->getPathname();
    $relativePath = str_replace(__DIR__ . '/../../', '', $filePath);

    // Read file content
    $content = file_get_contents($filePath);

    // Check for DataProvider attribute
    if (strpos($content, '#[DataProvider') !== false || strpos($content, 'DataProvider(') !== false) {
        echo "✓ Found #[DataProvider] in: {$relativePath}\n";

        // Try to extract namespace and class name
        preg_match('/namespace\s+([^;]+);/', $content, $namespaceMatches);
        preg_match('/class\s+(\w+)/', $content, $classMatches);

        if (! empty($namespaceMatches) && ! empty($classMatches)) {
            $fullClassName = $namespaceMatches[1] . '\\' . $classMatches[1];
            $foundClasses[] = $fullClassName;

            echo "  Class: {$fullClassName}\n";

            // Check if class can be loaded
            if (class_exists($fullClassName)) {
                echo "  ✓ Class can be loaded\n";

                // Check for attribute via reflection
                $reflection = new ReflectionClass($fullClassName);
                $attributes = $reflection->getAttributes(DataProvider::class);

                if (! empty($attributes)) {
                    echo "  ✓ DataProvider attribute found via reflection\n";
                    $attr = $attributes[0]->newInstance();
                    echo "    Name: {$attr->name}\n";
                } else {
                    echo "  ✗ No DataProvider attribute found via reflection!\n";
                }
            } else {
                echo "  ✗ Class cannot be loaded\n";
            }

            echo "\n";
        }
    }
}

if (empty($foundClasses)) {
    echo "✗ No classes with #[DataProvider] attribute found\n";
} else {
    echo "\nSummary:\n";
    echo "Found " . count($foundClasses) . " classes with #[DataProvider] attribute\n";
    foreach ($foundClasses as $class) {
        echo "  - {$class}\n";
    }
}
