<?php

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

// Simple debug TUI without complex dependencies
use App\Framework\Console\Components\TuiState;
use App\Framework\Console\Components\TuiInputHandler;
use App\Framework\Console\Components\TuiCommandExecutor;
use App\Framework\Console\CommandHistory;
use App\Framework\Console\TuiView;
use App\Framework\Console\TuiKeyCode;
use App\Framework\Console\ConsoleColor;
use App\Framework\Console\Screen\ScreenControlCode;
use App\Framework\Console\Screen\CursorControlCode;

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

// Check TTY
if (!posix_isatty(STDIN)) {
    echo "❌ Requires TTY. Run with: docker exec -it php php simple_debug_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 {
    // 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;
        }
    };

    // 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 index: $oldIndex → $newIndex\n";
            flush();
        }

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

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

    // 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' => "QUIT",
                default => "OTHER('$key')"
            };

            echo "\n[INPUT] 🎯 Key: $keyDesc (hex: $keyHex)\n";
            echo "[INPUT] 📍 Current view: " . $state->getCurrentView()->name . "\n";
            echo "[INPUT] 📍 Current category: " . $state->getSelectedCategory() . "\n";
            flush();

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

            echo "[INPUT] ✅ After processing - Category: " . $state->getSelectedCategory() . "\n";
            flush();
        }
    };

    $state = $debugState;
    $history = new CommandHistory();
    $inputHandler = $debugInputHandler;

    // 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 ready\n";
    echo "Categories: " . count($testCategories) . "\n";
    echo "Selected: " . $state->getSelectedCategory() . "\n\n";

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

    echo "Setting up terminal for PHPStorm...\n";

    // 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');
    }

    echo "✓ Terminal configured\n\n";

    echo "🚀 SIMPLE DEBUG TUI\n";
    echo "==================\n\n";

    function renderSimpleMenu($categories, $selectedIndex) {
        echo "Categories:\n";
        foreach ($categories as $index => $category) {
            $indicator = $index === $selectedIndex ? '▶️' : '  ';
            echo "$indicator {$category['icon']} {$category['name']}\n";
        }
        echo "\n";
    }

    function readKeyPHPStorm() {
        $key = fgetc(STDIN);
        if ($key === false) return '';

        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);
            return $sequence;
        }

        return $key;
    }

    // Simple debug loop
    echo "Use ↑/↓ arrow keys to navigate. Press 'q' to quit.\n\n";

    while ($state->isRunning()) {
        // Render current state
        renderSimpleMenu($testCategories, $state->getSelectedCategory());

        echo "Debug Info:\n";
        echo "- Selected Index: " . $state->getSelectedCategory() . "\n";
        echo "- Current View: " . $state->getCurrentView()->name . "\n";
        $category = $state->getCurrentCategory();
        echo "- Category Name: " . ($category ? $category['name'] : 'NULL') . "\n";
        echo "\nPress arrow keys...\n";
        echo str_repeat('=', 40) . "\n";

        // Read input
        $key = readKeyPHPStorm();

        if ($key === 'q' || $key === 'Q') {
            echo "\n[QUIT] Stopping TUI...\n";
            $state->setRunning(false);
            break;
        }

        if ($key !== '') {
            // Clear screen for next render
            echo ScreenControlCode::CLEAR_ALL->format();
            echo CursorControlCode::POSITION->format(1, 1);

            // Process input with full debug output
            $inputHandler->handleInput($key, $state, $history);

            echo "\n" . str_repeat('-', 40) . "\n";
        }
    }

} finally {
    // Restore terminal
    if (!empty($originalSettings)) {
        shell_exec("stty $originalSettings 2>/dev/null");
    }
    echo "\n✅ Simple Debug TUI ended\n";
}