import time
import ctypes
import struct
import sys

log_fp = open(r"c:\Projects\AutoPOE2\scratch\dodge_test.log", "w", encoding="utf-8")
old_print = print
def print(*args, **kwargs):
    old_print(*args, **kwargs)
    old_print(*args, **kwargs, file=log_fp)
    log_fp.flush()

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

def main():
    try:
        hwinsta = user32.OpenWindowStationW("WinSta0", False, 0x10000000)
        if hwinsta: user32.SetProcessWindowStation(hwinsta)
        hdesk = user32.OpenDesktopW("Default", 0, False, 0x10000000)
        if hdesk: user32.SetThreadDesktop(hdesk)
    except Exception as e:
        print(f"Desktop error: {e}")

    hwnd = user32.FindWindowW("POEWindowClass", None)
    if not hwnd: hwnd = user32.FindWindowW(None, "Path of Exile 2")
    if not hwnd: return

    user32.ShowWindow(hwnd, 9)
    user32.SetForegroundWindow(hwnd)
    time.sleep(0.3)

    # Click top border to focus
    user32.SetCursorPos(1280, 5)
    time.sleep(0.05)
    user32.mouse_event(0x0002, 0, 0, 0, 0)
    time.sleep(0.05)
    user32.mouse_event(0x0004, 0, 0, 0, 0)
    time.sleep(0.3)

    # Place cursor towards the open dirt road to the South-East (1800, 900)
    user32.SetCursorPos(1800, 900)
    time.sleep(0.1)

    pid = 43084
    h_proc = kernel32.OpenProcess(0x0410, False, pid)
    xyz_addr = 0x2AF791A0550

    def read_xyz():
        if not h_proc: return (0.0, 0.0, 0.0)
        buf = ctypes.create_string_buffer(12)
        br = ctypes.c_size_t(0)
        kernel32.ReadProcessMemory(h_proc, ctypes.c_void_p(xyz_addr), buf, 12, ctypes.byref(br))
        return struct.unpack('3f', buf.raw) if br.value == 12 else (0.0, 0.0, 0.0)

    print(f"Initial XYZ: {read_xyz()}")

    # Press Spacebar (VK 0x20, Scan 0x39) to Dodge Roll towards cursor!
    print("Pressing Spacebar (Dodge Roll)...")
    user32.keybd_event(0x20, 0x39, 0, 0)
    time.sleep(0.08)
    user32.keybd_event(0x20, 0x39, 2, 0)
    time.sleep(0.6)

    xyz_after = read_xyz()
    print(f"After Spacebar: {xyz_after}")

    # Also test holding 'D' + 'S' (South-East towards path) for 1.5s
    print("Holding 'D' + 'S' (South-East towards path)...")
    user32.keybd_event(0x44, 0x20, 0, 0) # 'D'
    user32.keybd_event(0x53, 0x1F, 0, 0) # 'S'
    time.sleep(1.5)
    user32.keybd_event(0x44, 0x20, 2, 0)
    user32.keybd_event(0x53, 0x1F, 2, 0)
    time.sleep(0.4)

    xyz_final = read_xyz()
    print(f"Final XYZ: {xyz_final}")

    # Capture screen
    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_dodge_after.png")

    if h_proc: kernel32.CloseHandle(h_proc)
    print("Done.")

if __name__ == "__main__":
    main()
