#!/bin/bash

# Setup Dual Keybindings for GNOME Desktop
# This script configures both dictation and conversation keybindings

DICTATION_SCRIPT="/mnt/storage/Development/dictation-service/scripts/toggle-dictation.sh"
CONVERSATION_SCRIPT="/mnt/storage/Development/dictation-service/scripts/toggle-conversation.sh"

DICTATION_NAME="Toggle Dictation"
DICTATION_BINDING="<Alt>d"
CONVERSATION_NAME="Toggle AI Conversation"
CONVERSATION_BINDING="<Super><Alt>d"

echo "Setting up dual mode keybindings..."

# --- Find or Create Custom Keybindings ---
KEYBASE="/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings"
declare -A KEYBINDINGS_TO_SETUP
KEYBINDINGS_TO_SETUP["$DICTATION_NAME"]="$DICTATION_SCRIPT:$DICTATION_BINDING"
KEYBINDINGS_TO_SETUP["$CONVERSATION_NAME"]="$CONVERSATION_SCRIPT:$CONVERSATION_BINDING"

declare -A EXISTING_KEYBINDING_PATHS
FULL_CUSTOM_PATHS=()

CURRENT_LIST_STR=$(gsettings get org.gnome.settings-daemon.plugins.media-keys custom-keybindings)
CURRENT_LIST_ARRAY=()

# Parse CURRENT_LIST_STR into an array
if [[ "$CURRENT_LIST_STR" != "@as []" ]]; then
    TEMP_STR=$(echo "$CURRENT_LIST_STR" | sed -e "s/^@as \[//g" -e "s/\]$//g" -e "s/'//g")
    IFS=',' read -ra CURRENT_LIST_ARRAY <<< "$TEMP_STR"
fi

for path_entry in "${CURRENT_LIST_ARRAY[@]}"; do
    path=$(echo "$path_entry" | xargs) # Trim whitespace
    if [ -n "$path" ]; then
        name=$(gsettings get org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$path"/ name 2>/dev/null)
        name_clean=$(echo "$name" | sed "s/'//g")
        
        if [[ -n "${KEYBINDINGS_TO_SETUP[$name_clean]}" ]]; then
            EXISTING_KEYBINDING_PATHS["$name_clean"]="$path"
        fi
        FULL_CUSTOM_PATHS+=("$path")
    fi
done

# Process each desired keybinding
for KB_NAME in "${!KEYBINDINGS_TO_SETUP[@]}"; do
    KB_VALUE=${KEYBINDINGS_TO_SETUP[$KB_NAME]}
    KB_SCRIPT=$(echo "$KB_VALUE" | cut -d':' -f1)
    KB_BINDING=$(echo "$KB_VALUE" | cut -d':' -f2)

    if [ -n "${EXISTING_KEYBINDING_PATHS[$KB_NAME]}" ]; then
        # Update existing keybinding
        KEY_PATH="${EXISTING_KEYBINDING_PATHS[$KB_NAME]}"
        echo "Updating existing keybinding for '$KB_NAME' at: $KEY_PATH"
        gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$KEY_PATH"/ command "'$KB_SCRIPT'"
        gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$KEY_PATH"/ binding "'$KB_BINDING'"
        gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$KEY_PATH"/ name "'$KB_NAME'"
    else
        # Create new keybinding slot
        NEXT_NUM=0
        for path_entry in "${FULL_CUSTOM_PATHS[@]}"; do
            path_num=$(echo "$path_entry" | sed -n 's/.*custom\([0-9]\+\)$/\1/p')
            if [ -n "$path_num" ] && [ "$path_num" -ge "$NEXT_NUM" ]; then
                NEXT_NUM=$((path_num + 1))
            fi
        done
        
        NEW_KEY_ID="custom$NEXT_NUM"
        NEW_FULL_PATH="$KEYBASE/$NEW_KEY_ID/"
        
        echo "Creating new keybinding for '$KB_NAME' at: $NEW_FULL_PATH"
        gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$NEW_FULL_PATH" name "'$KB_NAME'"
        gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$NEW_FULL_PATH" command "'$KB_SCRIPT'"
        gsettings set org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$NEW_FULL_PATH" binding "'$KB_BINDING'"
        
        FULL_CUSTOM_PATHS+=("$NEW_FULL_PATH")
    fi
done

# Update the main custom-keybindings list to include only the paths we've configured/updated
# Filter out any non-existent paths (e.g. if custom keybindings were manually removed)
VALID_PATHS=()
for path in "${FULL_CUSTOM_PATHS[@]}"; do
    name=$(gsettings get org.gnome.settings-daemon.plugins.media-keys.custom-keybinding:"$path"/ name 2>/dev/null)
    if [[ -n "$name" && ( "$name" == "'$DICTATION_NAME'" || "$name" == "'$CONVERSATION_NAME'" ) ]]; then
        VALID_PATHS+=("'$path'")
    fi
done

IFS=',' NEW_LIST="[$(echo "${VALID_PATHS[*]}" | sed 's/ /,/g')]"
gsettings set org.gnome.settings-daemon.plugins.media-keys custom-keybindings "$NEW_LIST"

echo "Dual keybinding setup complete!"
echo ""
echo "🎤 Dictation Mode:     $DICTATION_BINDING"
echo "🤖 Conversation Mode:  $CONVERSATION_BINDING"
echo ""
echo "Dictation mode transcribes your voice to text."
echo "Conversation mode lets you talk with an AI assistant."
echo ""
echo "Note: Keybindings will only function if the 'dictation.service' is running and ydotoold is active."
echo "To remove these keybindings later, you might need to manually check"
echo "your GNOME Keyboard Shortcuts settings or use dconf-editor."