import time
import ctypes
import os
import sys
from ctypes import wintypes

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

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

class INPUT(ctypes.Structure):
    class _INPUT_UNION(ctypes.Union):
        _fields_ = [("ki", KEYBDINPUT)]
    _anonymous_ = ("_u",)
    _fields_ = [
        ("type", wintypes.DWORD),
        ("_u", _INPUT_UNION)
    ]

KEYEVENTF_SCANCODE = 0x0008
KEYEVENTF_KEYUP = 0x0002
INPUT_KEYBOARD = 1

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

def send_scancode_up(scan):
    inp = INPUT(type=INPUT_KEYBOARD)
    inp.ki.wVk = 0
    inp.ki.wScan = scan
    inp.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP
    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


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

    # Click safe screen center to guarantee input focus
    user32.SetCursorPos(1280, 500)
    time.sleep(0.05)
    # Left click once
    user32.mouse_event(0x0002, 0, 0, 0, 0) # LEFTDOWN
    time.sleep(0.03)
    user32.mouse_event(0x0004, 0, 0, 0, 0) # LEFTUP
    time.sleep(0.2)

    # Press ESC to close any open panels/chat
    send_scancode_down(0x01) # ESC scan code
    time.sleep(0.05)
    send_scancode_up(0x01)
    time.sleep(0.3)

    # Open process for reading XYZ
    pid = 43084
    h_proc = kernel32.OpenProcess(0x0010, 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)
        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 SendInput with W (Scan 0x11) for 1 second
    xyz_before = read_xyz()
    print("Holding 'W' via SendInput KEYEVENTF_SCANCODE for 1.2 seconds...")
    send_scancode_down(0x11) # W scan code
    time.sleep(1.2)
    send_scancode_up(0x11)
    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"W: Before {xyz_before} -> After {xyz_after} | Delta=({dx:.2f}, {dy:.2f}) Dist={dist:.2f}")

    # Test SendInput with S (Scan 0x1F) for 1.2 seconds
    xyz_before = read_xyz()
    print("Holding 'S' via SendInput KEYEVENTF_SCANCODE for 1.2 seconds...")
    send_scancode_down(0x1F) # S scan code
    time.sleep(1.2)
    send_scancode_up(0x1F)
    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"S: Before {xyz_before} -> After {xyz_after} | Delta=({dx:.2f}, {dy:.2f}) Dist={dist:.2f}")

    # Capture result
    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_sendinput_after.png")

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

if __name__ == "__main__":
    main()
