<?php

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

echo "Interactive Input Test\n";
echo "=====================\n\n";

echo "This test requires a real TTY terminal.\n";
echo "Run with: docker exec -it php php test_interactive_input.php\n\n";

// Check if we have a TTY
if (!posix_isatty(STDIN)) {
    echo "❌ ERROR: This script requires a TTY terminal.\n";
    echo "Current environment is not a TTY.\n";
    echo "Please run with: docker exec -it php php test_interactive_input.php\n";
    exit(1);
}

echo "✓ TTY detected. Terminal is interactive.\n\n";

// Check stty availability
if (!function_exists('shell_exec') || shell_exec('which stty') === null) {
    echo "❌ ERROR: stty command not available.\n";
    echo "Raw mode setup will not work.\n";
    exit(1);
}

echo "✓ stty command available.\n\n";

echo "Setting up raw mode...\n";

// Save current terminal settings
$originalSettings = trim(shell_exec('stty -g'));
echo "✓ Original terminal settings saved: $originalSettings\n";

// Set raw mode
shell_exec('stty -icanon -echo');
echo "✓ Raw mode enabled.\n\n";

echo "=== ARROW KEY TEST ===\n";
echo "Press arrow keys to test. Press 'q' to quit.\n";
echo "You should see the exact key codes being detected.\n\n";

function readKeySequence(): string {
    $key = fgetc(STDIN);
    if ($key === false) {
        return '';
    }

    // Handle escape sequences
    if ($key === "\033") {
        $sequence = $key;

        // Read next character with timeout
        stream_set_blocking(STDIN, false);
        $next = fgetc(STDIN);
        stream_set_blocking(STDIN, true);

        if ($next === false) {
            return $key; // Just escape
        }
        $sequence .= $next;

        // If it's a bracket, read more
        if ($next === '[') {
            stream_set_blocking(STDIN, false);
            $third = fgetc(STDIN);
            stream_set_blocking(STDIN, true);

            if ($third !== false) {
                $sequence .= $third;

                // Some sequences have more characters
                if (in_array($third, ['5', '6', '3', '1', '2', '4'])) {
                    stream_set_blocking(STDIN, false);
                    $fourth = fgetc(STDIN);
                    stream_set_blocking(STDIN, true);

                    if ($fourth !== false) {
                        $sequence .= $fourth;
                    }
                }
            }
        }

        return $sequence;
    }

    return $key;
}

try {
    $testCount = 0;
    while (true) {
        $key = readKeySequence();

        if ($key === 'q' || $key === 'Q') {
            echo "\nQuitting...\n";
            break;
        }

        if ($key !== '') {
            $testCount++;
            $hexKey = bin2hex($key);
            $asciiKey = addcslashes($key, "\0..\37\177..\377");

            echo "Test $testCount:\n";
            echo "  Raw: '$asciiKey'\n";
            echo "  Hex: $hexKey\n";
            echo "  Bytes: " . strlen($key) . "\n";

            switch ($key) {
                case "\033[A":
                    echo "  ✓ ARROW UP detected correctly!\n";
                    break;
                case "\033[B":
                    echo "  ✓ ARROW DOWN detected correctly!\n";
                    break;
                case "\033[C":
                    echo "  ✓ ARROW RIGHT detected correctly!\n";
                    break;
                case "\033[D":
                    echo "  ✓ ARROW LEFT detected correctly!\n";
                    break;
                case "\n":
                case "\r":
                    echo "  ✓ ENTER detected!\n";
                    break;
                case " ":
                    echo "  ✓ SPACE detected!\n";
                    break;
                case "\033":
                    echo "  ✓ ESC detected!\n";
                    break;
                case "\177":
                case "\x08":
                    echo "  ✓ BACKSPACE detected!\n";
                    break;
                default:
                    if (ctype_print($key)) {
                        echo "  → Regular key: '$key'\n";
                    } else {
                        echo "  → Special key (unknown)\n";
                    }
                    break;
            }
            echo "\n";
        }

        // Add small delay to prevent CPU spinning
        usleep(50000); // 50ms
    }
} finally {
    // Always restore terminal settings
    echo "Restoring terminal settings...\n";
    shell_exec("stty $originalSettings");
    echo "✓ Terminal restored.\n";
    echo "\nTest completed. Total inputs processed: $testCount\n";
}