"""Translate blessed Keystroke objects to pyos integer key codes."""

from . import Keys
from .EventTypes import KeyState

_BLESSED_NAME_MAP = {
    "KEY_UP": Keys.UP,
    "KEY_DOWN": Keys.DOWN,
    "KEY_LEFT": Keys.LEFT,
    "KEY_RIGHT": Keys.RIGHT,
    "KEY_HOME": Keys.HOME,
    "KEY_END": Keys.END,
    "KEY_ENTER": Keys.ENTER,
    "KEY_BACKSPACE": Keys.BACKSPACE,
    "KEY_F(1)": Keys.F1,
    "KEY_F(2)": Keys.F2,
    "KEY_F(3)": Keys.F3,
    "KEY_F(4)": Keys.F4,
    "KEY_F(5)": Keys.F5,
    "KEY_F(6)": Keys.F6,
    "KEY_ESCAPE": Keys.ESC,
    "KEY_TAB": Keys.TAB,
}


def blessed_keystroke_state(keystroke):
    """Extract KeyState from a blessed Keystroke object."""
    if getattr(keystroke, 'released', False):
        return KeyState.RELEASED
    if getattr(keystroke, 'repeated', False):
        return KeyState.REPEATED
    return KeyState.PRESSED


def blessed_key_to_int(keystroke):
    """Convert a blessed Keystroke to a pyos integer key code.

    Returns None for empty/timeout keystrokes.
    """
    if not keystroke:
        return None

    # Named sequences (arrows, function keys, etc.)
    if keystroke.name:
        code = _BLESSED_NAME_MAP.get(keystroke.name)
        if code is not None:
            return code

    # Regular printable / control characters
    if keystroke:
        code = keystroke.code
        if code is not None:
            return code
        # Fall back to ord of the character value
        s = str(keystroke)
        if len(s) == 1:
            return ord(s)

    return None
