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

log_fp = open(r"c:\Projects\AutoPOE2\scratch\focus_keys.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

ULONG_PTR = ctypes.c_uint64

class KEYBDINPUT(ctypes.Structure):
    _fields_ = [
        ('wVk', wintypes.WORD),
        ('wScan', wintypes.WORD),
        ('dwFlags', wintypes.DWORD),
        ('time', wintypes.DWORD),
        ('dwExtraInfo', ULONG_PTR),
    ]

class MOUSEINPUT(ctypes.Structure):
    _fields_ = [
        ('dx', wintypes.LONG),
        ('dy', wintypes.LONG),
        ('mouseData', wintypes.DWORD),
        ('dwFlags', wintypes.DWORD),
        ('time', wintypes.DWORD),
        ('dwExtraInfo', ULONG_PTR),
    ]

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = [
        ('uMsg', wintypes.DWORD),
        ('wParamL', wintypes.WORD),
        ('wParamH', wintypes.WORD),
    ]

class INPUT_UNION(ctypes.Union):
    _fields_ = [
        ('mi', MOUSEINPUT),
        ('ki', KEYBDINPUT),
        ('hi', HARDWAREINPUT),
    ]

class INPUT(ctypes.Structure):
    _anonymous_ = ('u',)
    _fields_ = [
        ('type', wintypes.DWORD),
        ('u', INPUT_UNION),
    ]

def send_scancode_down(scan):
    inp = INPUT(type=1)
    inp.ki.wVk = 0
    inp.ki.wScan = scan
    inp.ki.dwFlags = 0x0008 # KEYEVENTF_SCANCODE
    return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT))

def send_scancode_up(scan):
    inp = INPUT(type=1)
    inp.ki.wVk = 0
    inp.ki.wScan = scan
    inp.ki.dwFlags = 0x0008 | 0x0002
    return user32.SendInput(1, ctypes.byref(inp), ctypes.sizeof(INPUT))

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")
    print(f"HWND: {hwnd}")
    if not hwnd: return

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

    # Click top edge (1280, 2) to give focus without triggering skills
    user32.SetCursorPos(1280, 2)
    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)

    fg = user32.GetForegroundWindow()
    print(f"Foreground HWND: {fg} (Expected: {hwnd})")

    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()}")

    # Test 1: SendInput Scancode 'W' (0x11) for 1.5s
    xyz_before = read_xyz()
    print("\n--- Test 1: SendInput Scancode 'W' (0x11) for 1.5s ---")
    r1 = send_scancode_down(0x11)
    time.sleep(1.5)
    r2 = send_scancode_up(0x11)
    time.sleep(0.4)
    xyz_after = read_xyz()
    print(f"SendInput W (r1={r1}, r2={r2}): Before {xyz_before} -> After {xyz_after}")

    # Test 2: SendInput Scancode 'D' (0x20) for 1.5s
    xyz_before = read_xyz()
    print("\n--- Test 2: SendInput Scancode 'D' (0x20) for 1.5s ---")
    r1 = send_scancode_down(0x20)
    time.sleep(1.5)
    r2 = send_scancode_up(0x20)
    time.sleep(0.4)
    xyz_after = read_xyz()
    print(f"SendInput D (r1={r1}, r2={r2}): Before {xyz_before} -> After {xyz_after}")

    # Test 3: keybd_event 'W' (VK 0x57, scan 0x11) for 1.5s
    xyz_before = read_xyz()
    print("\n--- Test 3: keybd_event 'W' for 1.5s ---")
    user32.keybd_event(0x57, 0x11, 0, 0)
    time.sleep(1.5)
    user32.keybd_event(0x57, 0x11, 2, 0)
    time.sleep(0.4)
    xyz_after = read_xyz()
    print(f"keybd_event W: Before {xyz_before} -> After {xyz_after}")

    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_focus_keys_after.png")

    if h_proc: kernel32.CloseHandle(h_proc)
    print("\nDone.")

if __name__ == "__main__":
    main()
