#!/usr/bin/env php
<?php
declare(strict_types=1);

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

use App\Framework\Core\AppBootstrapper;
use App\Framework\Performance\EnhancedPerformanceCollector;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemHighResolutionClock;
use App\Framework\Performance\MemoryMonitor;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\Console\ConsoleCommand;
use App\Framework\Context\ExecutionContext;

echo "=== Debug: Make Console Issue ===" . PHP_EOL;
echo "Current environment:" . PHP_EOL;
echo "  TERM: " . ($_SERVER['TERM'] ?? 'not set') . PHP_EOL;
echo "  STDIN: " . (stream_isatty(STDIN) ? 'TTY' : 'not TTY') . PHP_EOL;
echo "  STDOUT: " . (stream_isatty(STDOUT) ? 'TTY' : 'not TTY') . PHP_EOL;
echo "  argv[0]: " . ($_SERVER['argv'][0] ?? 'not set') . PHP_EOL;
echo "  Command line: " . implode(' ', $_SERVER['argv'] ?? []) . PHP_EOL;

try {
    echo "1. Creating components..." . PHP_EOL;
    $clock = new SystemClock();
    $highResClock = new SystemHighResolutionClock();
    $memoryMonitor = new MemoryMonitor();
    $collector = new EnhancedPerformanceCollector($clock, $highResClock, $memoryMonitor, enabled: false);
    $bootstrapper = new AppBootstrapper(__DIR__, $collector, $memoryMonitor);
    
    echo "2. Detecting execution context..." . PHP_EOL;
    $context = ExecutionContext::detect();
    echo "   Context type: " . $context->getType()->value . PHP_EOL;
    
    echo "3. Bootstrapping console..." . PHP_EOL;
    $consoleApp = $bootstrapper->bootstrapConsole();
    
    echo "4. Getting container..." . PHP_EOL;
    $reflection = new ReflectionClass($consoleApp);
    $containerProperty = $reflection->getProperty('container');
    $containerProperty->setAccessible(true);
    $container = $containerProperty->getValue($consoleApp);
    
    echo "5. Checking DiscoveryRegistry..." . PHP_EOL;
    if ($container->has(DiscoveryRegistry::class)) {
        $discoveryRegistry = $container->get(DiscoveryRegistry::class);
        $commands = $discoveryRegistry->attributes->get(ConsoleCommand::class);
        echo "   ConsoleCommand attributes: " . count($commands) . PHP_EOL;
        
        if (count($commands) > 0) {
            echo "   First 3 commands:" . PHP_EOL;
            foreach (array_slice($commands, 0, 3) as $discovered) {
                $command = $discovered->createAttributeInstance();
                echo "     - " . $command->name . PHP_EOL;
            }
        }
    } else {
        echo "   DiscoveryRegistry NOT found!" . PHP_EOL;
    }
    
    echo "6. Checking CommandRegistry..." . PHP_EOL;
    $registryProperty = $reflection->getProperty('commandRegistry');
    $registryProperty->setAccessible(true);
    $commandRegistry = $registryProperty->getValue($consoleApp);
    
    if ($commandRegistry) {
        $commandRegistryReflection = new ReflectionClass($commandRegistry);
        $commandListProperty = $commandRegistryReflection->getProperty('commandList');
        $commandListProperty->setAccessible(true);
        $commandList = $commandListProperty->getValue($commandRegistry);
        
        if ($commandList) {
            echo "   CommandList count: " . $commandList->count() . PHP_EOL;
        } else {
            echo "   CommandList is NULL!" . PHP_EOL;
        }
    } else {
        echo "   CommandRegistry is NULL!" . PHP_EOL;
    }
    
    echo "7. Cache key analysis..." . PHP_EOL;
    $pathProvider = $container->get(\App\Framework\Core\PathProvider::class);
    $currentContext = ExecutionContext::detect();
    $contextString = $currentContext->getType()->value;
    $defaultPaths = [$pathProvider->getSourcePath()];
    
    echo "   Context: " . $contextString . PHP_EOL;
    echo "   Paths: " . implode(', ', $defaultPaths) . PHP_EOL;
    
    // Generate cache key as it would be done in DiscoveryServiceBootstrapper
    $pathsHash = md5(implode('|', $defaultPaths));
    $cacheKey = "discovery:full_{$pathsHash}_{$contextString}";
    echo "   Expected cache key: " . $cacheKey . PHP_EOL;
    
} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . PHP_EOL;
    echo "Stack trace: " . $e->getTraceAsString() . PHP_EOL;
}