<?php

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

echo "PHPStorm Terminal Compatibility Test\n";
echo "====================================\n\n";

echo "Environment Analysis:\n";
echo "- TERM: " . (getenv('TERM') ?: 'not set') . "\n";
echo "- COLORTERM: " . (getenv('COLORTERM') ?: 'not set') . "\n";
echo "- TERMINAL_EMULATOR: " . (getenv('TERMINAL_EMULATOR') ?: 'not set') . "\n";
echo "- INSIDE_EMACS: " . (getenv('INSIDE_EMACS') ?: 'not set') . "\n";
echo "- IDE_PROJECT_ROOTS: " . (getenv('IDE_PROJECT_ROOTS') ?: 'not set') . "\n";

// Check if this looks like PHPStorm/IntelliJ
$isPhpStorm = getenv('TERMINAL_EMULATOR') === 'JetBrains-JediTerm' ||
              !empty(getenv('IDE_PROJECT_ROOTS')) ||
              strpos(getenv('TERM') ?: '', 'jetbrains') !== false;

echo "- Detected PHPStorm: " . ($isPhpStorm ? 'YES' : 'NO') . "\n";

// TTY check
$hasTTY = posix_isatty(STDIN);
echo "- Has TTY: " . ($hasTTY ? 'YES' : 'NO') . "\n";

// STDIN properties
echo "- STDIN is resource: " . (is_resource(STDIN) ? 'YES' : 'NO') . "\n";
echo "- STDIN type: " . get_resource_type(STDIN) . "\n";

// stty availability
$hasStty = function_exists('shell_exec') && !empty(shell_exec('which stty 2>/dev/null'));
echo "- stty available: " . ($hasStty ? 'YES' : 'NO') . "\n";

if ($hasStty) {
    $sttySettings = trim(shell_exec('stty -a 2>/dev/null') ?: '');
    echo "- Current stty settings: " . (!empty($sttySettings) ? 'available' : 'unavailable') . "\n";
}

echo "\n";

if (!$hasTTY) {
    echo "❌ No TTY available. TUI will not work in this environment.\n";
    echo "Try running in a real terminal instead of PHPStorm's integrated terminal.\n";
    exit(1);
}

if (!$hasStty) {
    echo "❌ stty command not available. Raw mode cannot be set.\n";
    exit(1);
}

echo "Setting up PHPStorm-compatible input reading...\n\n";

// Save original settings
$originalSettings = trim(shell_exec('stty -g') ?: '');
if (empty($originalSettings)) {
    echo "❌ Could not save terminal settings\n";
    exit(1);
}

echo "✓ Original settings saved\n";

// PHPStorm-specific terminal setup
echo "Setting up terminal for PHPStorm...\n";

// Try different approaches for PHPStorm
if ($isPhpStorm) {
    echo "Using PHPStorm-optimized settings...\n";
    // PHPStorm sometimes needs different settings
    shell_exec('stty raw -echo min 1 time 0 2>/dev/null');
} else {
    echo "Using standard settings...\n";
    shell_exec('stty -icanon -echo 2>/dev/null');
}

echo "✓ Raw mode set\n\n";

echo "=== INPUT TEST ===\n";
echo "Press keys to test input. Type 'quit' to exit.\n";
echo "Pay attention to arrow key behavior.\n\n";

function readInput(): string {
    $input = '';

    while (true) {
        $char = fgetc(STDIN);
        if ($char === false) {
            break;
        }

        $input .= $char;

        // Check for complete escape sequence
        if ($char === "\033") {
            // Read potential escape sequence
            $next = fgetc(STDIN);
            if ($next !== false) {
                $input .= $next;
                if ($next === '[') {
                    $third = fgetc(STDIN);
                    if ($third !== false) {
                        $input .= $third;
                        // Some sequences have a 4th character
                        if (in_array($third, ['5', '6', '3', '1', '2', '4'])) {
                            $fourth = fgetc(STDIN);
                            if ($fourth !== false) {
                                $input .= $fourth;
                            }
                        }
                    }
                }
            }
            break;
        }

        // For regular characters, break immediately
        if ($char !== "\033") {
            break;
        }
    }

    return $input;
}

try {
    $buffer = '';
    $testCount = 0;

    while (true) {
        $key = readInput();

        if ($key === '') {
            continue;
        }

        $testCount++;
        $buffer .= $key;

        echo "Input $testCount:\n";
        echo "  Raw: '" . addcslashes($key, "\0..\37\177..\377") . "'\n";
        echo "  Hex: " . bin2hex($key) . "\n";
        echo "  Length: " . strlen($key) . "\n";

        // Check for complete words
        if (str_contains($buffer, 'quit')) {
            echo "Quit command detected!\n";
            break;
        }

        // Analyze the key
        switch ($key) {
            case "\033[A":
                echo "  ✓ ARROW UP - Perfect!\n";
                break;
            case "\033[B":
                echo "  ✓ ARROW DOWN - Perfect!\n";
                break;
            case "\033[C":
                echo "  ✓ ARROW RIGHT - Perfect!\n";
                break;
            case "\033[D":
                echo "  ✓ ARROW LEFT - Perfect!\n";
                break;
            case "\n":
            case "\r":
                echo "  ✓ ENTER\n";
                $buffer = ''; // Reset buffer on enter
                break;
            case "\033":
                echo "  → ESC (incomplete sequence?)\n";
                break;
            default:
                if (ctype_print($key)) {
                    echo "  → Character: '$key'\n";
                } else {
                    echo "  → Special/Unknown\n";
                }
                break;
        }

        echo "\n";

        // Limit output to prevent spam
        if ($testCount > 20) {
            echo "Test limit reached. Type 'quit' to exit.\n";
        }
    }

} finally {
    echo "\nRestoring terminal...\n";
    shell_exec("stty $originalSettings 2>/dev/null");
    echo "✓ Terminal restored\n";
    echo "Total inputs processed: $testCount\n";
}

echo "\n=== RECOMMENDATIONS ===\n";

if ($isPhpStorm) {
    echo "PHPStorm Terminal detected. Consider:\n";
    echo "1. Use external terminal (Windows Terminal, iTerm2, etc.)\n";
    echo "2. Or use PHPStorm's 'Terminal' tool window with different shell\n";
    echo "3. Some TUI features may be limited in integrated terminals\n";
} else {
    echo "Standard terminal detected. TUI should work normally.\n";
}

echo "\nIf arrow keys didn't work properly, the TUI navigation will also fail.\n";