import time
import ctypes
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, get_client_rect, 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)

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

user32 = ctypes.windll.user32
VK_W = 0x57
SC_W = 0x11
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101

# Send W for 0.8s
t_end = time.time() + 0.8
while time.time() < t_end:
    user32.PostMessageW(hwnd, WM_KEYDOWN, VK_W, (SC_W << 16) | 1)
    user32.keybd_event(VK_W, SC_W, 0, 0)
    time.sleep(0.04)

user32.PostMessageW(hwnd, WM_KEYUP, VK_W, (SC_W << 16) | 0xC0000001)
user32.keybd_event(VK_W, SC_W, 2, 0)
time.sleep(0.5)

img_after = capture_window_bitblt(hwnd, client_only=True)
img_after.save("captures/test_wasd_after.png")
print("WASD test finished, saved captures/test_wasd_after.png")
