#!/usr/bin/env python3

import os
import subprocess
import time
from pynput import keyboard
from pynput.keyboard import Key, KeyCode

# Configuration
DICTATION_DIR = "/mnt/storage/Development/dictation-service"
TOGGLE_DICTATION_SCRIPT = os.path.join(DICTATION_DIR, "scripts", "toggle-dictation.sh")
TOGGLE_CONVERSATION_SCRIPT = os.path.join(
    DICTATION_DIR, "scripts", "toggle-conversation.sh"
)

# Track key states
alt_pressed = False
super_pressed = False
d_pressed = False


def on_press(key):
    global alt_pressed, super_pressed, d_pressed

    if key == Key.alt_l or key == Key.alt_r:
        alt_pressed = True
    elif key == Key.cmd_l or key == Key.cmd_r:  # Super key
        super_pressed = True
    elif hasattr(key, "char") and key.char == "d":
        d_pressed = True

    # Check for Alt+D
    if alt_pressed and d_pressed and not super_pressed:
        try:
            subprocess.run([TOGGLE_DICTATION_SCRIPT], check=True)
            print("Alt+D pressed - toggled dictation")
        except subprocess.CalledProcessError as e:
            print(f"Error running dictation toggle: {e}")
        # Reset keys
        alt_pressed = d_pressed = False

    # Check for Super+Alt+D
    elif super_pressed and alt_pressed and d_pressed:
        try:
            subprocess.run([TOGGLE_CONVERSATION_SCRIPT], check=True)
            print("Super+Alt+D pressed - toggled conversation")
        except subprocess.CalledProcessError as e:
            print(f"Error running conversation toggle: {e}")
        # Reset keys
        super_pressed = alt_pressed = d_pressed = False


def on_release(key):
    global alt_pressed, super_pressed, d_pressed

    if key == Key.alt_l or key == Key.alt_r:
        alt_pressed = False
    elif key == Key.cmd_l or key == Key.cmd_r:
        super_pressed = False
    elif hasattr(key, "char") and key.char == "d":
        d_pressed = False


if __name__ == "__main__":
    print("Starting keybinding listener...")
    print("Alt+D: Toggle dictation")
    print("Super+Alt+D: Toggle conversation")

    with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()
