import time
import ctypes
from ctypes import wintypes
import struct

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

def focus_poe2():
    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: return False
    
    user32.ShowWindow(hwnd, 5)
    user32.SetForegroundWindow(hwnd)
    user32.BringWindowToTop(hwnd)
    time.sleep(0.1)

    # Click top border (1280, 5) to guarantee input focus in Windows 11
    user32.SetCursorPos(1280, 5)
    user32.mouse_event(2, 0, 0, 0, 0)
    time.sleep(0.02)
    user32.mouse_event(4, 0, 0, 0, 0)
    time.sleep(0.1)
    return True

def read_xyz(h_process):
    xyz_addr = 0x2AF791A0550
    buf = ctypes.create_string_buffer(12)
    bytes_read = ctypes.c_size_t()
    if kernel32.ReadProcessMemory(h_process, ctypes.c_void_p(xyz_addr), buf, 12, ctypes.byref(bytes_read)):
        return struct.unpack("<fff", buf.raw)
    return None

def main():
    if not focus_poe2():
        print("Cannot focus PoE2 window!")
        return

    pid = 43084
    PROCESS_VM_READ = 0x0010
    h_process = kernel32.OpenProcess(PROCESS_VM_READ, False, pid)
    if not h_process:
        print(f"Cannot open process {pid}")
        return

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

    # Move cursor to center-right area to aim path (e.g. 1500, 700)
    user32.SetCursorPos(1500, 700)
    time.sleep(0.05)

    # Press 'W' for 500ms
    scan_w = user32.MapVirtualKeyW(0x57, 0)
    print(f"Sending KEYDOWN 'W' (scan={hex(scan_w)})...")
    user32.keybd_event(0x57, scan_w, 0, 0)
    time.sleep(0.5)
    user32.keybd_event(0x57, scan_w, 2, 0)
    print("Sent KEYUP 'W'")

    time.sleep(0.2)
    xyz_after = read_xyz(h_process)
    print(f"XYZ After: {xyz_after}")

    kernel32.CloseHandle(h_process)

    # Capture screen
    import sys
    sys.path.insert(0, 'tools')
    from autonomous_map_runner import ScreenCapturerGDI
    capturer = ScreenCapturerGDI()
    capturer.capture('captures/test_live_wasd_result.png')
    print("Captured captures/test_live_wasd_result.png")

if __name__ == '__main__':
    main()
