<?php

declare(strict_types=1);

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

use App\Framework\Cache\Driver\InMemoryCache;
use App\Framework\Cache\GeneralCache;
use App\Framework\Core\PathProvider;
use App\Framework\DateTime\SystemClock;
use App\Framework\DI\DefaultContainer;
use App\Framework\Discovery\Factory\DiscoveryServiceFactory;
use App\Framework\Discovery\ValueObjects\DiscoveryConfiguration;
use App\Framework\Serializer\Json\JsonSerializer;

echo "=== Deep Debug of Memory-Managed Chunking ===\n\n";

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

    $container = new DefaultContainer();
    $pathProvider = new PathProvider($projectRoot);
    $clock = new SystemClock();
    $cacheDriver = new InMemoryCache();
    $serializer = new JsonSerializer();
    $cache = new GeneralCache($cacheDriver, $serializer);

    $factory = new DiscoveryServiceFactory($container, $pathProvider, $cache, $clock);

    // Create memory-managed service with development config
    $memoryConfig = DiscoveryConfiguration::development()->withPaths([$srcPath]);

    echo "Development config:\n";
    print_r($memoryConfig->toArray());
    echo "\n";

    // Use reflection to create service with custom config
    $reflection = new ReflectionClass($factory);
    $createMethod = $reflection->getMethod('create');
    $createMethod->setAccessible(true);

    $memoryService = $createMethod->invoke($factory, $memoryConfig);

    // Add debug logging by enabling logger
    $serviceReflection = new ReflectionClass($memoryService);
    $loggerProp = $serviceReflection->getProperty('logger');
    $loggerProp->setAccessible(true);

    // Create a simple debug logger
    $debugLogger = new class () {
        public function debug(string $message, array $context = []): void
        {
            echo "[DEBUG] $message\n";
            if (! empty($context)) {
                echo "  Context: " . json_encode($context, JSON_PRETTY_PRINT) . "\n";
            }
        }

        public function info(string $message, array $context = []): void
        {
            echo "[INFO] $message\n";
            if (! empty($context)) {
                echo "  Context: " . json_encode($context, JSON_PRETTY_PRINT) . "\n";
            }
        }

        public function warning(string $message, array $context = []): void
        {
            echo "[WARNING] $message\n";
            if (! empty($context)) {
                echo "  Context: " . json_encode($context, JSON_PRETTY_PRINT) . "\n";
            }
        }

        public function error(string $message, array $context = []): void
        {
            echo "[ERROR] $message\n";
            if (! empty($context)) {
                echo "  Context: " . json_encode($context, JSON_PRETTY_PRINT) . "\n";
            }
        }

        public function critical(string $message, array $context = []): void
        {
            echo "[CRITICAL] $message\n";
            if (! empty($context)) {
                echo "  Context: " . json_encode($context, JSON_PRETTY_PRINT) . "\n";
            }
        }
    };

    $loggerProp->setValue($memoryService, $debugLogger);

    echo "=== Starting Memory-Managed Discovery with Debug Logging ===\n";
    $startTime = microtime(true);
    $registry = $memoryService->discover();
    $endTime = microtime(true);

    echo "\n=== Discovery Results ===\n";
    echo "Total items: " . count($registry) . "\n";
    echo "Initializers: " . $registry->attributes->getCount('App\\Framework\\DI\\Initializer') . "\n";
    echo "Processing time: " . round(($endTime - $startTime) * 1000, 2) . "ms\n";

    // Get memory statistics
    echo "\n=== Memory Statistics ===\n";
    $memoryStats = $memoryService->getMemoryStatistics();
    print_r($memoryStats);

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