"""
HotkeyManager — Global macOS System-Wide Shortcuts for Subify v3.0 Ultra
"""

import objc
import AppKit
from AppKit import (
    NSEvent, NSEventMaskKeyDown,
    NSEventModifierFlagOption, NSEventModifierFlagCommand
)


class HotkeyManager:
    """Manages system-wide global hotkeys for Subify."""

    def __init__(self, app_controller):
        self._app = app_controller
        self._monitor = None

    def start(self):
        try:
            self._monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
                NSEventMaskKeyDown, self._handle_event
            )
        except Exception:
            pass

    def stop(self):
        if self._monitor:
            try:
                NSEvent.removeMonitor_(self._monitor)
            except Exception:
                pass
            self._monitor = None

    def _handle_event(self, event):
        flags = event.modifierFlags()
        # Require Option (Alt) + Command modifiers
        is_opt_cmd = ((flags & NSEventModifierFlagOption) != 0) and ((flags & NSEventModifierFlagCommand) != 0)

        if not is_opt_cmd:
            return

        key_code = event.keyCode()

        # ⌥⌘L: Toggle Subtitles
        if key_code == 37:
            if self._app:
                self._app.performSelectorOnMainThread_withObject_waitUntilDone_(
                    'toggleOverlay:', None, False
                )

        # ⌥⌘→: Delay Lyrics (+0.5s)
        elif key_code == 124:
            if self._app:
                self._app.performSelectorOnMainThread_withObject_waitUntilDone_(
                    'quickDelaySync:', None, False
                )

        # ⌥⌘←: Advance Lyrics (-0.5s)
        elif key_code == 123:
            if self._app:
                self._app.performSelectorOnMainThread_withObject_waitUntilDone_(
                    'quickAdvanceSync:', None, False
                )

        # ⌥⌘D: Toggle Full Lyrics Drawer
        elif key_code == 2:
            if self._app:
                self._app.performSelectorOnMainThread_withObject_waitUntilDone_(
                    'toggleLyricsDrawer:', None, False
                )
