import time
import ctypes
from ctypes import wintypes
import struct
import sys

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

def read_xyz():
    pid = 43084
    h = kernel32.OpenProcess(0x0010, False, pid)
    if not h: return None
    buf = ctypes.create_string_buffer(12)
    br = ctypes.c_size_t()
    kernel32.ReadProcessMemory(h, ctypes.c_void_p(0x2AF791A0550), buf, 12, ctypes.byref(br))
    kernel32.CloseHandle(h)
    return struct.unpack("<fff", buf.raw)

def focus_properly():
    hwinsta = user32.OpenWindowStationW("WinSta0", False, 0x10000000)
    if hwinsta: user32.SetProcessWindowStation(hwinsta)
    hdesk = user32.OpenDesktopW("Default", 0, False, 0x10000000)
    if hdesk: user32.SetThreadDesktop(hdesk)

    hwnd = user32.FindWindowW("POEWindowClass", None)
    if not hwnd: hwnd = user32.FindWindowW(None, "Path of Exile 2")
    if not hwnd:
        print("Window not found!")
        return False

    user32.ShowWindow(hwnd, 9)
    cur_thread = kernel32.GetCurrentThreadId()
    fg_hwnd = user32.GetForegroundWindow()
    fg_thread = user32.GetWindowThreadProcessId(fg_hwnd, None)
    target_thread = user32.GetWindowThreadProcessId(hwnd, None)

    user32.AttachThreadInput(cur_thread, target_thread, True)
    user32.SetForegroundWindow(hwnd)
    user32.BringWindowToTop(hwnd)
    user32.SetFocus(hwnd)
    user32.AttachThreadInput(cur_thread, target_thread, False)
    time.sleep(0.2)

    # Check if fg_hwnd is now our game
    new_fg = user32.GetForegroundWindow()
    print(f"Foreground HWND: {hex(new_fg)} (target: {hex(hwnd)})")
    if new_fg != hwnd:
        # Fallback click on very top-left pixel (0, 0)
        user32.SetCursorPos(0, 0)
        user32.mouse_event(0x0002, 0, 0, 0, 0)
        time.sleep(0.02)
        user32.mouse_event(0x0004, 0, 0, 0, 0)
        time.sleep(0.5) # Wait 500ms for any potential action to finish
    return True

def main():
    if not focus_properly(): return

    # Let any previous animation settle
    time.sleep(0.8)

    xyz0 = read_xyz()
    print(f"XYZ Before: {xyz0}")

    # Move cursor to direction of movement (e.g. Center-Right: 1600, 720)
    user32.SetCursorPos(1600, 720)
    time.sleep(0.05)

    # Let's test pressing 'D' (Right: scan 0x20, VK 0x44) and 'W' (Up: scan 0x11, VK 0x57)
    # in PoE2 WASD:
    # W = Up, D = Right. Press both for 1.2 seconds to move North-East along the stream!
    print("Holding W + D for 1200ms...")
    user32.keybd_event(0x57, 0x11, 0, 0) # W down
    user32.keybd_event(0x44, 0x20, 0, 0) # D down
    time.sleep(1.2)
    user32.keybd_event(0x57, 0x11, 2, 0) # W up
    user32.keybd_event(0x44, 0x20, 2, 0) # D up
    print("Released W + D")

    time.sleep(0.3)
    xyz1 = read_xyz()
    print(f"XYZ After: {xyz1}")
    dx = xyz1[0] - xyz0[0]
    dy = xyz1[1] - xyz0[1]
    print(f"Delta: dX={dx:.2f}, dY={dy:.2f}")

    sys.path.insert(0, r"C:\Projects\AutoPOE2")
    from tools.autonomous_map_runner import ScreenCapturerGDI
    c = ScreenCapturerGDI()
    c.capture(r"C:\Projects\AutoPOE2\captures\test_wd_move_result.png")
    print("Captured test_wd_move_result.png")

if __name__ == '__main__':
    main()
