import sys
import time
import ctypes
from ctypes import wintypes
sys.path.insert(0, r"c:\Projects\AutoPOE2")
from src.common.win32_window import attach_to_default_desktop, find_poe2_window

attach_to_default_desktop()
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

hwnd = find_poe2_window()
# Re-attach to default desktop after find_poe2_window
attach_to_default_desktop()

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

print(f"Cur TID: {cur_tid}")
print(f"FG HWND: {hex(fg)}, PID: {fg_pid.value}, TID: {fg_tid}")
print(f"PoE2 HWND: {hex(hwnd)}, PID: {poe_pid.value}, TID: {poe_tid}")

# 1. Attach cur_tid to fg_tid (the foreground thread!)
att_fg = user32.AttachThreadInput(cur_tid, fg_tid, True)
print(f"Attach to FG thread: {att_fg}")

# 2. Attach cur_tid to poe_tid
att_poe = user32.AttachThreadInput(cur_tid, poe_tid, True)
print(f"Attach to PoE2 thread: {att_poe}")

# 3. Try SetForegroundWindow with Alt key trick
user32.keybd_event(0x12, 0, 0, 0) # Alt down
res_bring = user32.BringWindowToTop(hwnd)
res_sfw = user32.SetForegroundWindow(hwnd)
res_act = user32.SetActiveWindow(hwnd)
res_foc = user32.SetFocus(hwnd)
user32.keybd_event(0x12, 0, 2, 0) # Alt up

print(f"BringWindowToTop: {res_bring}, SetForegroundWindow: {res_sfw}, SetActive: {hex(res_act)}, SetFocus: {hex(res_foc)}")
time.sleep(0.1)

fg_after = user32.GetForegroundWindow()
print(f"FG AFTER SFW: {hex(fg_after)} (Expected {hex(hwnd)})")

# Detach
if att_poe:
    user32.AttachThreadInput(cur_tid, poe_tid, False)
if att_fg:
    user32.AttachThreadInput(cur_tid, fg_tid, False)

if fg_after == hwnd:
    print("🎉 SUCCESS! PoE2 IS NOW FOREGROUND WINDOW!")
else:
    print("Failed to set foreground.")
