<?php

declare(strict_types=1);

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

use App\Framework\Core\AppBootstrapper;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\DI\Container;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\LiveComponents\Attributes\DataProvider;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\Performance\MemoryMonitor;

echo "\nAttribute Discovery Debug\n";
echo str_repeat('=', 70) . "\n\n";

// 1. Bootstrap Application
echo "1. Bootstrapping Application...\n";
$basePath = dirname(__DIR__, 2);
$clock = new SystemClock();
$highResClock = new SystemHighResolutionClock();
$memoryMonitor = new MemoryMonitor();
$collector = new EnhancedPerformanceCollector($clock, $highResClock, $memoryMonitor, enabled: false);
$bootstrapper = new AppBootstrapper($basePath, $collector, $memoryMonitor);
$app = $bootstrapper->bootstrapConsole();
echo "✓ Application bootstrapped\n\n";

// 2. Get DiscoveryRegistry via reflection (since we can't access Container)
echo "2. Getting DiscoveryRegistry via reflection hack...\n";

try {
    // Hack: Get container via reflection
    $reflection = new ReflectionClass($bootstrapper);
    $containerProp = $reflection->getProperty('container');
    $containerProp->setAccessible(true);
    $container = $containerProp->getValue($bootstrapper);

    echo "✓ Got Container via reflection\n";

    // Get DiscoveryRegistry
    $discoveryRegistry = $container->get(DiscoveryRegistry::class);
    echo "✓ Got DiscoveryRegistry from Container\n\n";
} catch (\Exception $e) {
    echo "✗ FAILED: " . $e->getMessage() . "\n\n";
    exit(1);
}

// 3. Check if DataProvider attributes are discovered
echo "3. Checking for DataProvider attributes...\n";

try {
    $discoveredAttributes = $discoveryRegistry->attributes()->get(DataProvider::class);

    echo "  Discovered attributes count: " . count($discoveredAttributes) . "\n\n";

    if (count($discoveredAttributes) === 0) {
        echo "✗ PROBLEM: No DataProvider attributes found!\n";
        echo "  This means Discovery is not finding the #[DataProvider] attributes\n\n";
        echo "  Possible causes:\n";
        echo "  - Discovery cache is outdated\n";
        echo "  - DemoChartDataProvider file not scanned\n";
        echo "  - Attribute not correctly defined\n\n";
        exit(1);
    }

    // 4. List all discovered DataProvider classes
    echo "4. Discovered DataProvider classes:\n";
    foreach ($discoveredAttributes as $i => $discovered) {
        $className = $discovered->className->getFullyQualified();
        $arguments = $discovered->arguments;

        echo "  [" . ($i + 1) . "] Class: {$className}\n";
        echo "      Interface: " . ($arguments['interface'] ?? 'N/A') . "\n";
        echo "      Name: " . ($arguments['name'] ?? 'N/A') . "\n";
        echo "      Target: " . $discovered->target->value . "\n\n";
    }

} catch (\Exception $e) {
    echo "✗ FAILED: " . $e->getMessage() . "\n";
    echo "  File: " . $e->getFile() . ":" . $e->getLine() . "\n\n";
    exit(1);
}

// 5. Check if DemoChartDataProvider is in the list
echo "5. Checking for DemoChartDataProvider specifically...\n";

$foundDemo = false;
foreach ($discoveredAttributes as $discovered) {
    $className = $discovered->className->getFullyQualified();
    if (str_contains($className, 'DemoChartDataProvider')) {
        $foundDemo = true;
        echo "✓ DemoChartDataProvider found in discovery!\n";
        echo "  Full class name: {$className}\n";
        echo "  Arguments: " . json_encode($discovered->arguments, JSON_PRETTY_PRINT) . "\n\n";

        break;
    }
}

if (! $foundDemo) {
    echo "✗ PROBLEM: DemoChartDataProvider not found in discovered attributes\n";
    echo "  This means the file is not being scanned or attribute is missing\n\n";
    exit(1);
}

// 6. Check if DataProviderResolver is registered
echo "6. Checking if DataProviderResolver is registered...\n";

try {
    $hasResolver = $container->has(\App\Framework\LiveComponents\DataProviderResolver::class);

    if ($hasResolver) {
        echo "✓ DataProviderResolver is registered in Container\n\n";
    } else {
        echo "✗ PROBLEM: DataProviderResolver is NOT registered in Container\n";
        echo "  This means DataProviderResolverInitializer is not working\n\n";
        exit(1);
    }
} catch (\Exception $e) {
    echo "✗ FAILED: " . $e->getMessage() . "\n\n";
    exit(1);
}

// 7. Check if DemoChartDataProvider is registered in Container
echo "7. Checking if DemoChartDataProvider is registered in Container...\n";

$demoClassName = 'App\Application\LiveComponents\Services\DemoChartDataProvider';

try {
    $hasDemo = $container->has($demoClassName);

    if ($hasDemo) {
        echo "✓ DemoChartDataProvider is registered in Container\n";

        // Try to instantiate it
        $instance = $container->get($demoClassName);
        echo "✓ DemoChartDataProvider can be instantiated\n";
        echo "  Instance class: " . get_class($instance) . "\n\n";
    } else {
        echo "✗ PROBLEM: DemoChartDataProvider is NOT registered in Container\n";
        echo "  This means DataProviderRegistrationInitializer is not working\n\n";
        exit(1);
    }
} catch (\Exception $e) {
    echo "✗ FAILED: " . $e->getMessage() . "\n";
    echo "  This means registration or instantiation failed\n\n";
    exit(1);
}

// Summary
echo str_repeat('=', 70) . "\n";
echo "✅ DISCOVERY SYSTEM WORKING CORRECTLY\n\n";

echo "Summary:\n";
echo "- DiscoveryRegistry accessible ✓\n";
echo "- DataProvider attributes discovered ✓\n";
echo "- DemoChartDataProvider found in discovery ✓\n";
echo "- DataProviderResolver registered ✓\n";
echo "- DemoChartDataProvider registered ✓\n\n";

echo "If discovery is working but HTTP request fails,\n";
echo "the problem is in DataProviderResolver.findProviderClass() logic\n";
