import time
import ctypes
from ctypes import wintypes
import sys
from pathlib import Path

sys.path.insert(0, str(Path(".").resolve()))
from src.common.win32_window import find_poe2_window, attach_to_window_desktop, ensure_window_focus
from src.common.screen_capture import capture_window_bitblt

hwnd = find_poe2_window()
print("HWND:", hex(hwnd))
attach_to_window_desktop(hwnd)
ensure_window_focus(hwnd)

class KEYBDINPUT(ctypes.Structure):
    _fields_ = [
        ("wVk", wintypes.WORD),
        ("wScan", wintypes.WORD),
        ("dwFlags", wintypes.DWORD),
        ("time", wintypes.DWORD),
        ("dwExtraInfo", ctypes.c_ulonglong),
    ]

class INPUT_UNION(ctypes.Union):
    _fields_ = [("ki", KEYBDINPUT)]

class INPUT(ctypes.Structure):
    _fields_ = [
        ("type", wintypes.DWORD),
        ("_pad", wintypes.DWORD),
        ("i", INPUT_UNION),
    ]

def send_key_down_up(vk, scan, duration=0.8):
    KEYEVENTF_SCANCODE = 0x0008
    KEYEVENTF_KEYUP = 0x0002
    
    # Key down
    inp_down = INPUT()
    inp_down.type = 1
    inp_down.i.ki.wVk = vk
    inp_down.i.ki.wScan = scan
    inp_down.i.ki.dwFlags = KEYEVENTF_SCANCODE
    ctypes.windll.user32.SendInput(1, ctypes.byref(inp_down), ctypes.sizeof(INPUT))
    
    time.sleep(duration)
    
    # Key up
    inp_up = INPUT()
    inp_up.type = 1
    inp_up.i.ki.wVk = vk
    inp_up.i.ki.wScan = scan
    inp_up.i.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP
    ctypes.windll.user32.SendInput(1, ctypes.byref(inp_up), ctypes.sizeof(INPUT))

img_before = capture_window_bitblt(hwnd, client_only=True)
img_before.save("captures/test_sendinput_before.png")

print("Sending W keydown via SendInput for 0.8s on window desktop...")
send_key_down_up(0x57, 0x11, duration=0.8)
time.sleep(0.3)

img_after = capture_window_bitblt(hwnd, client_only=True)
img_after.save("captures/test_sendinput_after.png")
print("Saved captures/test_sendinput_after.png")
