"""Non-blocking keyboard input for pause/resume."""

import sys

try:
    import select
    import termios
    import tty
    _HAS_TTY = True
except ImportError:
    _HAS_TTY = False


class RawInput:
    """Context manager for non-blocking key reading via cbreak mode."""

    def __init__(self):
        self._old_settings = None
        self._active = False

    def __enter__(self):
        if _HAS_TTY and sys.stdin.isatty():
            self._old_settings = termios.tcgetattr(sys.stdin)
            tty.setcbreak(sys.stdin.fileno())
            self._active = True
        return self

    def __exit__(self, *exc):
        if self._old_settings is not None:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self._old_settings)
            self._old_settings = None
            self._active = False

    def get_key(self, timeout: float = 0.0) -> str | None:
        """Non-blocking key read. Returns single char or None."""
        if not self._active:
            return None
        ready, _, _ = select.select([sys.stdin], [], [], timeout)
        if ready:
            return sys.stdin.read(1)
        return None
