#!/bin/bash

# Define modifier flags as associative array for name lookup
# per https://github.com/hyprwm/Hyprland/blob/main/src/devices/IKeyboard.hpp#L13-L22
declare -A MODIFIER_NAMES=(
    [$((1 << 0))]="SHIFT"
    [$((1 << 1))]="CAPS"
    [$((1 << 2))]="CTRL"
    [$((1 << 3))]="ALT"
    [$((1 << 4))]="MOD2"
    [$((1 << 5))]="MOD3"
    [$((1 << 6))]="SUPER"
    [$((1 << 7))]="MOD5"
)

decode_modmask() {
    local modifiers=$1
    local result=()

    for bit in "${!MODIFIER_NAMES[@]}"; do
        if (( modifiers & bit )); then
            result+=("${MODIFIER_NAMES[$bit]}")
        fi
    done

    # Output all detected modifiers (plus-separated)
    echo "${result[*]}"
}

# Read live keybinds, not config file
OLD_IFS=$IFS
IFS=$'\n'
readarray -t KEYBINDS < <(hyprctl -j binds | jq -cr '.[]')
IFS=$OLD_IFS

# Loop over each keybind and pipe results to wofi for inspection/execution
# Format to send to wofi:
#
# <dispatcher> -- <arg> #<Modifier Keys> <Key> - <Description>
# exec -- alacritty #SUPER return - Launch a Terminal
# or
# exit -- #SUPER+ALT ESCAPE - Logout
#
# Wofi's pre-display-cmd looks for the '#' and prints everything after it
# in the wofi window. When we pipe that to `xargs hyprctl dispatch`, the
# Comment character ensures we ignore the description text and only executes
# the dispatcher + arg.
for keyconfig in "${KEYBINDS[@]}"; do
    # Use pipe '|' to delimit results
    IFS="|" read modmask key keycode description dispatcher arg < <(echo $(echo "$keyconfig" | jq -r '[.modmask, .key, .keycode, .description, .dispatcher, .arg] | join("|")'))
    keys=($(decode_modmask $modmask) $key)
    IFS=$OLD_IFS

    # We can't use IFS here, as it only supports single characters
    delimiter=" + "

    # Join the array elements with the delimiter
    combo=$(printf "%s$delimiter" "${keys[@]}")

    # Remove the trailing delimiter
    combo="${combo%$delimiter}"

    printf "%s -- %s #%-30s → %s\n" "$dispatcher" "$arg" "$combo" "$description"
done | flock --nonblock /tmp/.wofi.lock -c "wofi --cache-file /dev/null --width 40% --height 70% -d -i -p 'Hyprland Keybindings' --style=\"$HOME/.local/share/omarchy/default/wofi/search.css\" -m --pre-display-cmd \"echo '%s' | cut -d'#' -f2 | tr -d '\n'\" | xargs hyprctl dispatch"
