import ctypes
from ctypes import wintypes
import sys
from pathlib import Path

sys.path.insert(0, str(Path(".").resolve()))
from src.common.win32_window import find_poe2_window, attach_to_window_desktop, is_poe2_pid

class GUITHREADINFO(ctypes.Structure):
    _fields_ = [
        ("cbSize", wintypes.DWORD),
        ("flags", wintypes.DWORD),
        ("hwndActive", wintypes.HWND),
        ("hwndFocus", wintypes.HWND),
        ("hwndCapture", wintypes.HWND),
        ("hwndMenuOwner", wintypes.HWND),
        ("hwndMoveSize", wintypes.HWND),
        ("hwndCaret", wintypes.HWND),
        ("rcCaret", wintypes.RECT),
    ]

def is_focused_new(hwnd: int) -> bool:
    attach_to_window_desktop(hwnd)
    user32 = ctypes.windll.user32
    fg = user32.GetForegroundWindow()
    if fg == hwnd:
        return True
    if fg:
        pid_target = wintypes.DWORD()
        user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid_target))
        pid_fg = wintypes.DWORD()
        user32.GetWindowThreadProcessId(fg, ctypes.byref(pid_fg))
        if pid_target.value and pid_target.value == pid_fg.value:
            return True
    # Fallback for virtual / isolated desktop
    if user32.IsWindow(hwnd) and user32.IsWindowVisible(hwnd) and not user32.IsIconic(hwnd):
        gui = GUITHREADINFO()
        gui.cbSize = ctypes.sizeof(GUITHREADINFO)
        tid = user32.GetWindowThreadProcessId(hwnd, None)
        if tid and user32.GetGUIThreadInfo(tid, ctypes.byref(gui)):
            if gui.hwndActive == hwnd or gui.hwndFocus == hwnd:
                return True
            if gui.hwndActive:
                pid_act = wintypes.DWORD()
                user32.GetWindowThreadProcessId(gui.hwndActive, ctypes.byref(pid_act))
                if pid_act.value and is_poe2_pid(pid_act.value):
                    return True
    return False

hwnd = find_poe2_window()
print(f"HWND: {hex(hwnd) if hwnd else None}")
if hwnd:
    print(f"is_focused_new: {is_focused_new(hwnd)}")
