import ctypes
import threading
import time

import win32api
import win32con
import win32gui
import win32service

h_desk = win32service.OpenDesktop("Default", 0, False, win32con.GENERIC_ALL)
ctypes.windll.user32.SetThreadDesktop(int(h_desk))

WM_HOTKEY = 0x0312
MOD_NONE = 0x0000
VK_F9 = 0x78
HOTKEY_ID = 1001

hotkey_fired = [False]

def wnd_proc(hwnd, msg, wparam, lparam):
    if msg == WM_HOTKEY and wparam == HOTKEY_ID:
        print("[TEST] WM_HOTKEY received in message window!", flush=True)
        hotkey_fired[0] = True
        return 0
    return win32gui.DefWindowProc(hwnd, msg, wparam, lparam)

def hotkey_thread():
    ctypes.windll.user32.SetThreadDesktop(int(h_desk))

    wc = win32gui.WNDCLASS()
    wc.lpfnWndProc = wnd_proc
    wc.lpszClassName = "POE2_Hotkey_Listener_Class"
    wc.hInstance = win32api.GetModuleHandle(None)

    class_atom = win32gui.RegisterClass(wc)
    hwnd = win32gui.CreateWindow(
        class_atom, "POE2_Hotkey_Window", 0, 0, 0, 0, 0, 0, 0, wc.hInstance, None
    )

    ret = ctypes.windll.user32.RegisterHotKey(hwnd, HOTKEY_ID, MOD_NONE, VK_F9)
    print(f"RegisterHotKey on message window: {ret}", flush=True)

    # Message pump
    win32gui.PumpMessages()

t = threading.Thread(target=hotkey_thread, daemon=True)
t.start()
time.sleep(0.2)

print("Simulating F9 keypress...")
ctypes.windll.user32.keybd_event(VK_F9, 0, 0, 0)
time.sleep(0.02)
ctypes.windll.user32.keybd_event(VK_F9, 0, 2, 0)
time.sleep(0.3)

print(f"Did hotkey fire? -> {hotkey_fired[0]}")
