"""
Keyboard input handling module
"""

import sys
import tty
import termios
from typing import Optional


class InputHandler:
    """Handles raw keyboard input from terminal"""

    # Special key codes
    ARROW_UP = "UP"
    ARROW_DOWN = "DOWN"
    ARROW_LEFT = "LEFT"
    ARROW_RIGHT = "RIGHT"
    ENTER = "ENTER"
    ESC = "ESC"
    CTRL_C = "CTRL_C"
    SPACE = " "
    BACKSPACE = "\x7f"  # DEL character (backspace)

    @staticmethod
    def read_single_key() -> Optional[str]:
        """
        Read a single key press from the terminal

        Returns:
            Key name or None if unable to read
        """
        try:
            # Save current terminal settings
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)

            try:
                # Set terminal to raw mode
                tty.setraw(fd)

                # Read input
                ch = sys.stdin.read(1)

                if ord(ch) == 3:  # Ctrl+C
                    return InputHandler.CTRL_C
                elif ord(ch) == 27:  # Escape sequence
                    # Read the escape sequence
                    ch2 = sys.stdin.read(1)
                    if ch2 == "[":
                        ch3 = sys.stdin.read(1)
                        if ch3 == "A":
                            return InputHandler.ARROW_UP
                        elif ch3 == "B":
                            return InputHandler.ARROW_DOWN
                        elif ch3 == "C":
                            return InputHandler.ARROW_RIGHT
                        elif ch3 == "D":
                            return InputHandler.ARROW_LEFT
                    return InputHandler.ESC
                elif ord(ch) == 13:  # Enter
                    return InputHandler.ENTER
                else:
                    return ch

            finally:
                # Restore terminal settings
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

        except (OSError, termios.error):
            # Fallback if terminal control fails
            return None
