<?php

declare(strict_types=1);

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

use App\Framework\Discovery\UnifiedDiscoveryService;
use App\Framework\Discovery\ValueObjects\DiscoveryOptions;
use App\Framework\Cache\Cache;
use App\Framework\Cache\CacheKey;
use App\Framework\Cache\CacheItem;
use App\Framework\Attributes\Route;

// Simple null cache for testing
$cache = new class implements Cache {
    public function get(CacheKey $key): ?CacheItem { return null; }
    public function set(CacheItem ...$items): bool { return true; }
    public function delete(CacheKey ...$keys): bool { return true; }
    public function clear(): bool { return true; }
    public function has(CacheKey $key): bool { return false; }
};

try {

    // Create discovery service
    $discoveryService = new UnifiedDiscoveryService($cache);

    // Perform discovery
    $options = new DiscoveryOptions(
        paths: [__DIR__ . '/src'],
        cachingEnabled: false,  // Disable caching for test
        attributeTypes: [Route::class]
    );

    $registry = $discoveryService->discover($options);

    $routes = $registry->getByAttribute(Route::class);

    echo "=== DISCOVERED ROUTES ===\n\n";
    echo "Total routes found: " . count($routes) . "\n\n";

    foreach ($routes as $discovered) {
        $routeAttr = $discovered->attribute->newInstance();
        $className = $discovered->className;
        $methodName = $discovered->methodName ?? '__invoke';

        echo "Route: {$routeAttr->method->value} {$routeAttr->path}\n";
        echo "  Class: {$className}\n";
        echo "  Method: {$methodName}\n";

        // Check for Campaign routes specifically
        if (str_contains($className, 'Campaign')) {
            echo "  ⭐ CAMPAIGN ROUTE\n";
        }

        echo "\n";
    }

    // Specifically search for PreSaveCampaign
    echo "\n=== SEARCHING FOR PreSaveCampaign ===\n";
    $found = false;
    foreach ($routes as $discovered) {
        if (str_contains($discovered->className, 'PreSaveCampaign')) {
            echo "✅ PreSaveCampaign FOUND!\n";
            echo "  Path: {$discovered->attribute->newInstance()->path}\n";
            $found = true;
        }
    }

    if (!$found) {
        echo "❌ PreSaveCampaign NOT FOUND in discovery!\n";
    }

} catch (\Exception $e) {
    echo "❌ Error during discovery: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "\nStack trace:\n";
    echo $e->getTraceAsString() . "\n";
}
