<?php

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

// Live debug version of TUI that shows what's happening
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\TuiView;
use App\Framework\Console\TuiKeyCode;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Console\ConsoleColor;
use App\Framework\Console\Screen\ScreenManager;
use App\Framework\Console\Screen\ScreenControlCode;
use App\Framework\Console\Screen\CursorControlCode;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\DI\Container;

echo "Live TUI Debug Session\n";
echo "======================\n\n";

// Check TTY
if (!posix_isatty(STDIN)) {
    echo "❌ Requires TTY. Run with: docker exec -it php php debug_live_tui.php\n";
    exit(1);
}

echo "✓ TTY available\n";

// Check PHPStorm
$isPhpStorm = getenv('TERMINAL_EMULATOR') === 'JetBrains-JediTerm';
echo "✓ PHPStorm detected: " . ($isPhpStorm ? "YES" : "NO") . "\n\n";

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

    $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 []; } };
        }
    };

    // Debug command executor
    $debugExecutor = new class implements TuiCommandExecutor {
        public function executeSelectedCommand(object $command): void {
            echo "\n🚀 EXECUTE: Selected command\n";
            sleep(1);
        }
        public function executeCommand(string $commandName): void {
            echo "\n🚀 EXECUTE: $commandName\n";
            sleep(1);
        }
        public function validateSelectedCommand(object $command): void {
            echo "\n✓ VALIDATE: Selected command\n";
            sleep(1);
        }
        public function validateCommand(string $commandName): void {
            echo "\n✓ VALIDATE: $commandName\n";
            sleep(1);
        }
        public function showSelectedCommandHelp(object $command): void {
            echo "\n📚 HELP: Selected command\n";
            sleep(1);
        }
        public function showCommandHelp(string $commandName): void {
            echo "\n📚 HELP: $commandName\n";
            sleep(1);
        }
        public function showAllCommandsHelp(): void {
            echo "\n📚 HELP: All commands\n";
            sleep(1);
        }
        public function startInteractiveForm(object $command, \App\Framework\Console\Components\TuiState $state): void {
            echo "\n📝 FORM: Start interactive form\n";
            sleep(1);
        }
        public function findCommandObject(string $commandName): ?object {
            return null;
        }
    };

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

    // Create output with debug info
    $output = new class extends ConsoleOutput {
        public function writeLine(string $line = '', ?ConsoleColor $color = null): void {
            // Show debug info for navigation updates
            if (str_contains($line, '▶')) {
                echo "\n[DEBUG] Navigation update detected: $line\n";
            }
            parent::writeLine($line, $color);
        }
    };

    $output->screen = new ScreenManager($output);

    // Custom TUI state with debug
    $debugState = new class extends TuiState {
        public function setSelectedCategory(int $index): void {
            $oldIndex = $this->getSelectedCategory();
            parent::setSelectedCategory($index);
            $newIndex = $this->getSelectedCategory();
            echo "\n[DEBUG] Category changed: $oldIndex → $newIndex\n";
        }

        public function navigateUp(): void {
            echo "\n[DEBUG] navigateUp() called\n";
            $before = $this->getSelectedCategory();
            parent::navigateUp();
            $after = $this->getSelectedCategory();
            echo "[DEBUG] navigateUp result: $before → $after\n";
        }

        public function navigateDown(): void {
            echo "\n[DEBUG] navigateDown() called\n";
            $before = $this->getSelectedCategory();
            parent::navigateDown();
            $after = $this->getSelectedCategory();
            echo "[DEBUG] navigateDown result: $before → $after\n";
        }
    };

    // Custom input handler with debug
    $debugInputHandler = new class($debugExecutor) extends TuiInputHandler {
        public function handleInput(string $key, \App\Framework\Console\Components\TuiState $state, \App\Framework\Console\CommandHistory $history): void {
            $keyHex = bin2hex($key);
            $keyDesc = match($key) {
                "\033[A" => "ARROW_UP",
                "\033[B" => "ARROW_DOWN",
                "\033[C" => "ARROW_RIGHT",
                "\033[D" => "ARROW_LEFT",
                "\n" => "ENTER",
                " " => "SPACE",
                "\033" => "ESC",
                'q' => "Q",
                default => "OTHER($key)"
            };

            echo "\n[DEBUG] INPUT: '$keyDesc' (hex: $keyHex) in view: " . $state->getCurrentView()->name . "\n";

            parent::handleInput($key, $state, $history);

            echo "[DEBUG] After input - Selected: " . $state->getSelectedCategory() . "\n";
        }
    };

    $state = $debugState;
    $history = new CommandHistory();
    $inputHandler = $debugInputHandler;
    $renderer = new TuiRenderer($output);
    $groupRegistry = new CommandGroupRegistry($discoveryRegistry);

    // Add test categories
    $testCategories = [
        ['name' => 'Testing', 'description' => 'Test commands', 'icon' => '🧪', 'commands' => []],
        ['name' => 'Demo', 'description' => 'Demo commands', 'icon' => '🎮', 'commands' => []],
        ['name' => 'Generator', 'description' => 'Code generation', 'icon' => '⚙️', 'commands' => []],
        ['name' => 'General', 'description' => 'General commands', 'icon' => '📂', 'commands' => []]
    ];

    $state->setCategories($testCategories);
    $state->setCurrentView(TuiView::CATEGORIES);
    $state->setRunning(true);

    echo "✓ Debug TUI components ready\n";
    echo "Categories: " . count($testCategories) . "\n";
    echo "Selected: " . $state->getSelectedCategory() . "\n\n";

    // Save terminal settings
    $originalSettings = trim(shell_exec('stty -g') ?: '');

    // Set up terminal
    if ($isPhpStorm) {
        shell_exec('stty raw -echo min 1 time 0 2>/dev/null');
    } else {
        shell_exec('stty -icanon -echo 2>/dev/null');
    }

    // Hide cursor
    echo CursorControlCode::HIDE->format();

    echo "🚀 LIVE DEBUG TUI STARTED\n";
    echo "Use arrow keys to test navigation.\n";
    echo "Press 'q' to quit.\n";
    echo "All navigation events will be logged below.\n\n";

    // Simple TUI loop with debug
    while ($state->isRunning()) {
        // Clear and render
        echo ScreenControlCode::CLEAR_ALL->format();
        echo CursorControlCode::POSITION->format(1, 1);

        // Render current state
        $renderer->render($state, $history);

        // Show debug info at bottom
        echo "\n" . str_repeat('=', 60) . "\n";
        echo "DEBUG INFO:\n";
        echo "Selected Category: " . $state->getSelectedCategory() . "\n";
        echo "Current View: " . $state->getCurrentView()->name . "\n";
        $category = $state->getCurrentCategory();
        echo "Category Name: " . ($category ? $category['name'] : 'NULL') . "\n";
        echo "Press arrow keys to test navigation...\n";

        // Read input with PHPStorm-compatible method
        $key = fgetc(STDIN);
        if ($key === false) continue;

        if ($key === "\033") {
            $sequence = $key;
            stream_set_blocking(STDIN, false);
            $next = fgetc(STDIN);
            if ($next === false) {
                usleep(10000);
                $next = fgetc(STDIN);
            }
            if ($next !== false) {
                $sequence .= $next;
                if ($next === '[') {
                    $third = fgetc(STDIN);
                    if ($third === false) {
                        usleep(10000);
                        $third = fgetc(STDIN);
                    }
                    if ($third !== false) {
                        $sequence .= $third;
                    }
                }
            }
            stream_set_blocking(STDIN, true);
            $key = $sequence;
        }

        if ($key === 'q' || $key === 'Q') {
            $state->setRunning(false);
            break;
        }

        // Process input
        $inputHandler->handleInput($key, $state, $history);
    }

} finally {
    // Restore terminal
    echo CursorControlCode::SHOW->format();
    if (!empty($originalSettings)) {
        shell_exec("stty $originalSettings 2>/dev/null");
    }
    echo "\n✓ Debug TUI session ended\n";
}