<?php

declare(strict_types=1);

// Simulate web context
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['HTTP_HOST'] = 'localhost';
$_SERVER['SERVER_NAME'] = 'localhost';
$_SERVER['REQUEST_URI'] = '/';

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

use App\Framework\Cache\Driver\InMemoryCache;
use App\Framework\Cache\GeneralCache;
use App\Framework\Context\ExecutionContext;
use App\Framework\Core\PathProvider;
use App\Framework\DateTime\SystemClock;
use App\Framework\DI\DefaultContainer;
use App\Framework\DI\InitializerMapper;
use App\Framework\Discovery\UnifiedDiscoveryService;
use App\Framework\Discovery\ValueObjects\DiscoveryConfiguration;
use App\Framework\Filesystem\FileSystemService;
use App\Framework\Reflection\CachedReflectionProvider;
use App\Framework\Serializer\Json\JsonSerializer;

echo "=== Testing Context Filtering in Web Context ===\n\n";

try {
    // Setup
    $projectRoot = dirname(__DIR__, 2);
    $srcPath = $projectRoot . '/src';

    $currentContext = ExecutionContext::detect();
    echo "Current execution context: " . $currentContext->getType()->value . "\n\n";

    $container = new DefaultContainer();
    $pathProvider = new PathProvider($projectRoot);
    $clock = new SystemClock();
    $fileSystemService = new FileSystemService();
    $reflectionProvider = new CachedReflectionProvider();

    // Create cache for discovery
    $cacheDriver = new InMemoryCache();
    $serializer = new JsonSerializer();
    $cache = new GeneralCache($cacheDriver, $serializer);

    // Create InitializerMapper
    $initializerMapper = new InitializerMapper();

    // Configure discovery
    $config = new DiscoveryConfiguration(
        paths: [$srcPath],
        attributeMappers: [$initializerMapper],
        targetInterfaces: [],
        useCache: false
    );

    // Create discovery service
    $discoveryService = new UnifiedDiscoveryService(
        pathProvider: $pathProvider,
        cache: $cache,
        clock: $clock,
        reflectionProvider: $reflectionProvider,
        configuration: $config,
        attributeMappers: [$initializerMapper],
        targetInterfaces: []
    );

    echo "Starting discovery scan...\n";

    $registry = $discoveryService->discover();

    echo "Discovery completed!\n\n";

    // Check for Initializers
    $initializerAttributeClass = 'App\\Framework\\DI\\Initializer';
    $initializers = $registry->attributes->get($initializerAttributeClass);

    echo "=== Context Filtering Analysis ===\n";
    echo "Total initializers found: " . count($initializers) . "\n\n";

    $allowedCount = 0;
    $blockedCount = 0;
    $noContextCount = 0;

    foreach ($initializers as $mapping) {
        $className = $mapping->class->getFullyQualified();
        $shortName = $mapping->class->getShortName();
        $initializerData = $mapping->mappedData;

        // Check context filtering logic
        $isAllowed = true;
        $contextInfo = "No context restriction";

        if (isset($initializerData['contexts'])) {
            $allowedContexts = $initializerData['contexts'];

            if ($allowedContexts === null) {
                $contextInfo = "Null contexts (allowed everywhere)";
                $noContextCount++;
            } elseif (is_array($allowedContexts)) {
                $contextInfo = "Contexts: " . json_encode($allowedContexts);
                $isAllowed = in_array($currentContext->getType(), $allowedContexts, true);

                if ($isAllowed) {
                    $allowedCount++;
                } else {
                    $blockedCount++;
                }
            }
        } else {
            $noContextCount++;
        }

        $status = $isAllowed ? "✅ ALLOWED" : "❌ BLOCKED";

        echo "$status $shortName\n";
        echo "   $contextInfo\n";

        // Debug the actual data structure
        if (isset($initializerData['contexts']) && ! $isAllowed) {
            echo "   DEBUG - Contexts data: " . var_export($initializerData['contexts'], true) . "\n";
            echo "   DEBUG - Current context type: " . var_export($currentContext->getType(), true) . "\n";
            echo "   DEBUG - Context type class: " . get_class($currentContext->getType()) . "\n";
        }

        echo "\n";
    }

    echo "=== Summary ===\n";
    echo "Total: " . count($initializers) . "\n";
    echo "Allowed: $allowedCount\n";
    echo "Blocked: $blockedCount\n";
    echo "No context restriction: $noContextCount\n";
    echo "Expected to run in WEB context: " . ($allowedCount + $noContextCount) . "\n";

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