import time
import ctypes
import struct

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

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)
user32.ShowWindow(hwnd, 9)
user32.SetForegroundWindow(hwnd)
user32.BringWindowToTop(hwnd)
time.sleep(0.2)

# Focus click
user32.SetCursorPos(1280, 5)
user32.mouse_event(0x0002, 0, 0, 0, 0)
time.sleep(0.02)
user32.mouse_event(0x0004, 0, 0, 0, 0)

# WAIT 1.0 full second for attack animation to completely finish!
time.sleep(1.0)

pid = 43084
h = kernel32.OpenProcess(0x0010, False, pid)
player_ptr = 0x2AF791A0010

def read_pos(offset):
    buf = ctypes.create_string_buffer(12)
    br = ctypes.c_size_t()
    kernel32.ReadProcessMemory(h, ctypes.c_void_p(player_ptr + offset), buf, 12, ctypes.byref(br))
    return struct.unpack("<fff", buf.raw)

pos0 = read_pos(0x6B0)
print(f"Pos 0x6B0 Before: {pos0}")

# Aim cursor towards South-East / East stream path: (2000, 900)
user32.SetCursorPos(2000, 900)
time.sleep(0.1)

# Press 'D' (scan 0x20) and 'S' (scan 0x1F) for 1500ms to walk along the stream curve!
print("Pressing 'D' + 'S' for 1500ms...")
user32.keybd_event(0x44, 0x20, 0, 0) # D down
user32.keybd_event(0x53, 0x1F, 0, 0) # S down
time.sleep(1.5)
user32.keybd_event(0x44, 0x20, 2, 0) # D up
user32.keybd_event(0x53, 0x1F, 2, 0) # S up
print("Released 'D' + 'S'")

time.sleep(0.3)
pos1 = read_pos(0x6B0)
print(f"Pos 0x6B0 After: {pos1}")
dx = pos1[0] - pos0[0]
dy = pos1[1] - pos0[1]
print(f"Delta: dX={dx:.2f}, dY={dy:.2f}")

kernel32.CloseHandle(h)

import sys
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_move_around_ruin.png")
print("Captured test_move_around_ruin.png")
