import ctypes
import time
import os
import sys
sys.path.insert(0, ".")

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

def force_foreground(hwnd: int) -> bool:
    if not hwnd or not user32.IsWindow(hwnd):
        return False

    # 1. Restore & Topmost
    user32.ShowWindow(hwnd, 9)  # SW_RESTORE
    HWND_TOPMOST = -1
    user32.SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, 0x0001 | 0x0002 | 0x0040)

    # 2. Attach thread input to current foreground
    cur_tid = kernel32.GetCurrentThreadId()
    fg_hwnd = user32.GetForegroundWindow()
    fg_tid = user32.GetWindowThreadProcessId(fg_hwnd, None) if fg_hwnd else 0
    target_tid = user32.GetWindowThreadProcessId(hwnd, None)

    if fg_tid and fg_tid != cur_tid:
        user32.AttachThreadInput(cur_tid, fg_tid, True)
    if target_tid and target_tid != cur_tid:
        user32.AttachThreadInput(cur_tid, target_tid, True)

    try:
        # Unlock SetForegroundWindow
        SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001
        user32.SystemParametersInfoW(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, 0x0002)
        if hasattr(user32, "LockSetForegroundWindow"):
            user32.LockSetForegroundWindow(2)
        if hasattr(user32, "AllowSetForegroundWindow"):
            user32.AllowSetForegroundWindow(-1)  # ASFW_ANY

        # Alt key press trick
        user32.keybd_event(0x12, 0, 0, 0)
        user32.BringWindowToTop(hwnd)
        user32.SetForegroundWindow(hwnd)
        user32.SetActiveWindow(hwnd)
        user32.keybd_event(0x12, 0, 2, 0)
    finally:
        if fg_tid and fg_tid != cur_tid:
            user32.AttachThreadInput(cur_tid, fg_tid, False)
        if target_tid and target_tid != cur_tid:
            user32.AttachThreadInput(cur_tid, target_tid, False)

    # 3. Click client area to guarantee keyboard focus
    rect = ctypes.wintypes.RECT()
    user32.GetClientRect(hwnd, ctypes.byref(rect))
    pt = ctypes.wintypes.POINT(0, 0)
    user32.ClientToScreen(hwnd, ctypes.byref(pt))
    cl, ct = pt.x, pt.y
    cw = rect.right - rect.left
    ch = rect.bottom - rect.top

    # Click inside client area (near bottom-right or safe center-right where no buttons exist)
    # At Hideout, (cl + cw - 100, ct + 100) is empty ocean
    safe_cx = cl + cw - 100
    safe_cy = ct + 100

    cur_pt = ctypes.wintypes.POINT()
    user32.GetCursorPos(ctypes.byref(cur_pt))
    orig_x, orig_y = cur_pt.x, cur_pt.y

    user32.SetCursorPos(safe_cx, safe_cy)
    time.sleep(0.05)
    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.05)
    user32.SetCursorPos(orig_x, orig_y)

    new_fg = user32.GetForegroundWindow()
    print(f"Target HWND: {hex(hwnd)}, New FG HWND: {hex(new_fg)}, Match: {new_fg == hwnd}")
    return new_fg == hwnd

if __name__ == "__main__":
    from src.common.win32_window import find_poe2_window
    hwnd = find_poe2_window()
    print(f"POE2 HWND: {hex(hwnd)}")
    if hwnd:
        ok = force_foreground(hwnd)
        print(f"Force foreground result: {ok}")
