#!/usr/bin/env bash

# This script lists Sway keybindings from the Sway config file and allows the user to select one via rofi dmenu.
# When a keybinding is selected, it executes the associated command.

CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/sway/config"

# Check if config file exists
if [[ ! -f "$CONFIG_FILE" ]]; then
    notify-send "Sway Keybindings" "Config file not found: $CONFIG_FILE" -u critical
    exit 1
fi

# Parse keybindings from config file
# Format: "Mod+Key → Command description"
keybindings=$(grep -E '^\s*bindsym' "$CONFIG_FILE" | \
    grep -v '^[[:space:]]*#' | \
    sed 's/^\s*bindsym\s*//' | \
    awk '{
        # Remove trailing inline comments
        sub(/\s+#.*$/, "")

        # Skip leading flags like --release, --locked, etc.
        i = 1
        while (i <= NF && $i ~ /^--/) { i++ }
        if (i > NF) next

        # Extract the key combination
        keys = $i; i++

        # Extract the command (remaining fields)
        cmd = ""
        for (j = i; j <= NF; j++) {
            if (j > i) cmd = cmd " "
            cmd = cmd $j
        }

        # Format: "Key → Command"
        # Clean up common modifier names for better display
        gsub(/\$mod/, "Mod", keys)
        gsub(/Shift/, "⇧", keys)
        gsub(/Control/, "Ctrl", keys)
        gsub(/\+/, " + ", keys)

        printf "%-35s → %s\n", keys, cmd
    }')

# Show in rofi and get selection
selected=$(echo "$keybindings" | rofi -i -dmenu -p "Sway Shortcuts" -theme-str 'window {width: 60%;}')

# If something was selected, extract and execute the command
if [[ -n "$selected" ]]; then
    # Extract the command part (after the arrow)
    command=$(echo "$selected" | sed 's/^[^→]*→\s*//')

    if [[ -n "$command" ]]; then
        # Execute the command through swaymsg
        swaymsg "$command"
    fi
fi