import time
import ctypes
import os
import sys
from pathlib import Path

# Log to file
log_fp = open(r"c:\Projects\AutoPOE2\scratch\key_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()

# Add src to path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src"))
from assistant_tool.core_shm_bridge import CoreShmBridge

def main():
    user32 = ctypes.windll.user32
    kernel32 = ctypes.windll.kernel32

    # Attach to desktop
    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:
        hwnd = user32.FindWindowW(None, "Path of Exile")
    print(f"[Focus] HWND: {hwnd}")
    if not hwnd:
        print("[Error] PoE 2 window not found!")
        return

    # Focus window
    user32.ShowWindow(hwnd, 9)  # SW_RESTORE
    user32.SetForegroundWindow(hwnd)
    user32.BringWindowToTop(hwnd)
    time.sleep(0.5)

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

    bridge = CoreShmBridge()
    if not bridge.connect():
        print("[Warning] Could not connect to SHM Bridge! Testing key events directly...")

    # Find PID
    pid = 43084
    h_proc = kernel32.OpenProcess(0x0010, False, pid) # PROCESS_VM_READ
    xyz_addr = 0x2AF791A0550

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

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

    # Test each direction: W, S, A, D, and Space
    keys = [
        ('W', 0x57, 0x11),
        ('S', 0x53, 0x1F),
        ('A', 0x41, 0x1E),
        ('D', 0x44, 0x20),
        ('SPACE', 0x20, 0x39)
    ]

    for name, vk, scan in keys:
        xyz_before = read_xyz()
        print(f"\n--- Testing '{name}' hold for 1000ms ---")
        user32.SetForegroundWindow(hwnd)
        time.sleep(0.05)

        user32.keybd_event(vk, scan, 0, 0)
        time.sleep(1.0 if name != 'SPACE' else 0.1)
        user32.keybd_event(vk, scan, 2, 0)
        
        time.sleep(0.4)
        xyz_after = read_xyz()
        dx = xyz_after[0] - xyz_before[0]
        dy = xyz_after[1] - xyz_before[1]
        dist = (dx*dx + dy*dy)**0.5
        print(f"{name}: Before {xyz_before} -> After {xyz_after} | Delta=({dx:.2f}, {dy:.2f}) Dist={dist:.2f}")

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

    if h_proc:
        kernel32.CloseHandle(h_proc)

    print("\n--- Test Complete ---")

if __name__ == "__main__":
    main()


