"""Input mapping – translates SDL2 events to abstract actions."""

from __future__ import annotations

import ctypes
from enum import Enum, auto
from typing import Optional

import sdl2


class Action(Enum):
    UP = auto()
    DOWN = auto()
    LEFT = auto()
    RIGHT = auto()
    CONFIRM = auto()    # A / Return
    BACK = auto()       # B / Escape
    PAGE_UP = auto()    # L shoulder / PageUp
    PAGE_DOWN = auto()  # R shoulder / PageDown
    HUD_MODE = auto()   # Y / H
    QUIT = auto()       # Start / Q


# Keyboard mapping (for desktop testing)
_KEY_MAP: dict[int, Action] = {
    sdl2.SDLK_UP: Action.UP,
    sdl2.SDLK_DOWN: Action.DOWN,
    sdl2.SDLK_LEFT: Action.PAGE_UP,
    sdl2.SDLK_RIGHT: Action.PAGE_DOWN,
    sdl2.SDLK_RETURN: Action.CONFIRM,
    sdl2.SDLK_SPACE: Action.CONFIRM,
    sdl2.SDLK_ESCAPE: Action.BACK,
    sdl2.SDLK_BACKSPACE: Action.BACK,
    sdl2.SDLK_q: Action.QUIT,
    sdl2.SDLK_h: Action.HUD_MODE,
    sdl2.SDLK_PAGEUP: Action.PAGE_UP,
    sdl2.SDLK_PAGEDOWN: Action.PAGE_DOWN,
}

# GameController button mapping (R36S / generic controller)
_BUTTON_MAP: dict[int, Action] = {
    sdl2.SDL_CONTROLLER_BUTTON_DPAD_UP: Action.UP,
    sdl2.SDL_CONTROLLER_BUTTON_DPAD_DOWN: Action.DOWN,
    sdl2.SDL_CONTROLLER_BUTTON_DPAD_LEFT: Action.PAGE_UP,
    sdl2.SDL_CONTROLLER_BUTTON_DPAD_RIGHT: Action.PAGE_DOWN,
    sdl2.SDL_CONTROLLER_BUTTON_A: Action.CONFIRM,
    sdl2.SDL_CONTROLLER_BUTTON_B: Action.BACK,
    sdl2.SDL_CONTROLLER_BUTTON_LEFTSHOULDER: Action.PAGE_UP,
    sdl2.SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: Action.PAGE_DOWN,
    sdl2.SDL_CONTROLLER_BUTTON_Y: Action.HUD_MODE,
    sdl2.SDL_CONTROLLER_BUTTON_START: Action.QUIT,
}


def map_key(event: sdl2.SDL_Event) -> Optional[Action]:
    """Map an SDL2 event to an abstract Action, or None."""
    if event.type == sdl2.SDL_KEYDOWN:
        return _KEY_MAP.get(event.key.keysym.sym)
    if event.type == sdl2.SDL_CONTROLLERBUTTONDOWN:
        return _BUTTON_MAP.get(event.cbutton.button)
    return None
