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)

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

cur_tid = kernel32.GetCurrentThreadId()
poe_pid = wintypes.DWORD()
poe_tid = user32.GetWindowThreadProcessId(hwnd, ctypes.byref(poe_pid))

print(f"Cur TID={cur_tid}, POE2 TID={poe_tid}, PID={poe_pid.value}")

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

# Attach our input queue to POE2's input queue
attached = bool(user32.AttachThreadInput(cur_tid, poe_tid, True))
print(f"AttachThreadInput: {attached}")

VK_W = 0x57
SC_W = 0x11
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101

try:
    # Set active window to hwnd
    user32.SetActiveWindow(hwnd)
    user32.SetFocus(hwnd)
    
    t_end = time.time() + 1.0
    first = True
    while time.time() < t_end:
        user32.keybd_event(VK_W, SC_W, 0, 0)
        lparam = (SC_W << 16) | (1 if first else 0x40000001)
        user32.PostMessageW(hwnd, WM_KEYDOWN, VK_W, lparam)
        first = False
        time.sleep(0.04)
        
    user32.keybd_event(VK_W, SC_W, 2, 0)
    user32.PostMessageW(hwnd, WM_KEYUP, VK_W, (SC_W << 16) | 0xC0000001)
finally:
    user32.AttachThreadInput(cur_tid, poe_tid, False)

time.sleep(0.4)
img_after = capture_window_bitblt(hwnd, client_only=True)
img_after.save("captures/test_attach_after.png")
print("Saved captures/test_attach_after.png")
