<?php

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

// Debug real TUI execution
use App\Framework\Console\Components\ConsoleTUI;
use App\Framework\Console\Components\TuiState;
use App\Framework\Console\Components\TuiInputHandler;
use App\Framework\Console\Components\TuiCommandExecutor;
use App\Framework\Console\Components\TuiRenderer;
use App\Framework\Console\CommandHistory;
use App\Framework\Console\CommandGroupRegistry;
use App\Framework\Console\SimpleWorkflowExecutor;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Console\Screen\ScreenManager;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\DI\Container;

echo "Debug Real TUI Execution\n";
echo "========================\n\n";

// Check TTY first
if (!posix_isatty(STDIN)) {
    echo "❌ This test requires a TTY terminal.\n";
    echo "Run with: docker exec -it php php debug_real_tui.php\n";
    exit(1);
}

echo "✓ TTY detected\n";

// Check stty
if (!function_exists('shell_exec') || shell_exec('which stty') === null) {
    echo "❌ stty not available\n";
    exit(1);
}

echo "✓ stty available\n\n";

try {
    // Create minimal dependencies
    $container = new \App\Framework\DI\DefaultContainer();

    // Create a minimal discovery registry
    $discoveryRegistry = new class implements DiscoveryRegistry {
        public function interfaces() {
            return new class {
                public function get(string $interface) { return []; }
            };
        }
        public function attributes() {
            return new class {
                public function get(string $attributeClass) { return []; }
            };
        }
    };

    // Create mock command executor
    $mockExecutor = new class implements TuiCommandExecutor {
        public function executeSelectedCommand(object $command): void {
            echo "\n🚀 Mock: Execute command\n";
        }
        public function executeCommand(string $commandName): void {
            echo "\n🚀 Mock: Execute command: $commandName\n";
        }
        public function validateSelectedCommand(object $command): void {
            echo "\n✓ Mock: Validate command\n";
        }
        public function validateCommand(string $commandName): void {
            echo "\n✓ Mock: Validate command: $commandName\n";
        }
        public function showSelectedCommandHelp(object $command): void {
            echo "\n📚 Mock: Show help\n";
        }
        public function showCommandHelp(string $commandName): void {
            echo "\n📚 Mock: Show help: $commandName\n";
        }
        public function showAllCommandsHelp(): void {
            echo "\n📚 Mock: Show all commands help\n";
        }
        public function startInteractiveForm(object $command, \App\Framework\Console\Components\TuiState $state): void {
            echo "\n📝 Mock: Start form\n";
        }
        public function findCommandObject(string $commandName): ?object {
            return null;
        }
    };

    // Create workflow executor
    $workflowExecutor = new class implements SimpleWorkflowExecutor {
        public function executeWorkflow(array $workflow, \App\Framework\Console\Components\TuiState $state): void {
            echo "\n🔄 Mock: Execute workflow\n";
        }
    };

    // Create components
    $output = new ConsoleOutput();
    $output->screen = new ScreenManager($output);

    $state = new TuiState();
    $history = new CommandHistory();
    $inputHandler = new TuiInputHandler($mockExecutor);
    $renderer = new TuiRenderer($output);
    $groupRegistry = new CommandGroupRegistry($discoveryRegistry);

    echo "✓ Components created\n";

    // Test categories loading
    $categories = $groupRegistry->getOrganizedCommands();
    echo "✓ Categories loaded: " . count($categories) . "\n";

    if (empty($categories)) {
        // Add test categories since discovery is empty
        $testCategories = [
            [
                'name' => 'Testing',
                'description' => 'Test commands',
                'icon' => '🧪',
                'priority' => 0,
                'commands' => []
            ],
            [
                'name' => 'Demo',
                'description' => 'Demo commands',
                'icon' => '🎮',
                'priority' => 0,
                'commands' => []
            ],
            [
                'name' => 'General',
                'description' => 'General commands',
                'icon' => '📂',
                'priority' => 0,
                'commands' => []
            ]
        ];
        $state->setCategories($testCategories);
        echo "✓ Test categories added: " . count($testCategories) . "\n";
    } else {
        $state->setCategories($categories);
    }

    // Create TUI
    $tui = new ConsoleTUI(
        $output,
        $container,
        $discoveryRegistry,
        $state,
        $renderer,
        $inputHandler,
        $mockExecutor,
        $history,
        $groupRegistry,
        $workflowExecutor
    );

    echo "✓ TUI created\n\n";

    echo "🚀 Starting TUI...\n";
    echo "Use arrow keys to navigate, 'q' to quit.\n";
    echo "This will show if the TUI actually responds to input.\n\n";

    // Start TUI
    $exitCode = $tui->run();

    echo "\n✓ TUI exited with code: " . $exitCode->value . "\n";

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