import os
import sys
import time
import ctypes
from ctypes import wintypes
import numpy as np

sys.path.insert(0, r"c:\Projects\AutoPOE2")

from src.common.win32_window import find_poe2_window, get_client_rect
from src.common.virtual_display_manager import capture_virtual_display

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

hwnd = find_poe2_window()
if not hwnd:
    print("PoE 2 window not found!")
    sys.exit(1)

cur_tid = kernel32.GetCurrentThreadId()
poe_pid = wintypes.DWORD()
poe_tid = user32.GetWindowThreadProcessId(hwnd, ctypes.byref(poe_pid))

fg_before = user32.GetForegroundWindow()
fg_title = ctypes.create_unicode_buffer(256)
user32.GetWindowTextW(fg_before, fg_title, 256)
print(f"Current Foreground Window: {hex(fg_before)} ('{fg_title.value}')")
print(f"PoE 2 HWND: {hex(hwnd)}, TID: {poe_tid}, PID: {poe_pid.value}, Our TID: {cur_tid}")

# 1. Capture before
img1 = capture_virtual_display()
img1.save("captures/test_attach_before.png")

# 2. Attach thread input
attached = user32.AttachThreadInput(cur_tid, poe_tid, True)
print(f"AttachThreadInput result: {attached}")

try:
    # SetActiveWindow and SetFocus to PoE 2
    act_res = user32.SetActiveWindow(hwnd)
    foc_res = user32.SetFocus(hwnd)
    print(f"SetActiveWindow: {hex(act_res)}, SetFocus: {hex(foc_res)}")

    # Check foreground window - ensure it did NOT steal focus
    fg_after = user32.GetForegroundWindow()
    fg_title2 = ctypes.create_unicode_buffer(256)
    user32.GetWindowTextW(fg_after, fg_title2, 256)
    print(f"Foreground Window After SetActive: {hex(fg_after)} ('{fg_title2.value}')")

    # Send W key via PostMessage for 1.0 second
    VK_W = 0x57
    SC_W = 0x11
    WM_KEYDOWN = 0x0100
    WM_KEYUP = 0x0101
    lparam_down = (SC_W << 16) | 1
    lparam_up = (SC_W << 16) | 0xC0000001

    print("Sending W key for 1.2s...")
    t_end = time.time() + 1.2
    while time.time() < t_end:
        user32.PostMessageW(hwnd, WM_KEYDOWN, VK_W, lparam_down)
        time.sleep(0.04)
    user32.PostMessageW(hwnd, WM_KEYUP, VK_W, lparam_up)
    time.sleep(0.3)

finally:
    # Always detach
    user32.AttachThreadInput(cur_tid, poe_tid, False)
    print("Detached thread input.")

# 3. Capture after
img2 = capture_virtual_display()
img2.save("captures/test_attach_after.png")

# 4. Compare
a1 = np.array(img1, dtype=np.float32)
a2 = np.array(img2, dtype=np.float32)
diff = np.abs(a2 - a1)
mean_diff = np.mean(diff)
player_diff = np.mean(diff[440:640, 860:1060])
print(f"Mean Diff: {mean_diff:.4f}, Player Diff: {player_diff:.4f}")
if player_diff > 10.0 or mean_diff > 5.0:
    print(">>> SUCCESS! CHARACTER MOVED! <<<")
else:
    print(f"Difference level: {mean_diff:.2f} (baseline ~2.0)")
