import os
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()
print(f"PoE2 HWND: {hex(hwnd)}")

# Coordinates of PoE2 center on virtual display:
# DISPLAY8 is at (1920, 0) to (3840, 1080).
# Center of PoE2 is (1920 + 960, 540) = (2880, 540)
target_x = 1920 + 960
target_y = 540

print(f"Setting physical cursor to ({target_x}, {target_y})...")
user32.SetCursorPos(target_x, target_y)
time.sleep(0.05)

# Mouse click down and up
MOUSEEVENTF_LEFTDOWN = 0x0002
MOUSEEVENTF_LEFTUP = 0x0004
user32.mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
time.sleep(0.05)
user32.mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
time.sleep(0.15)

fg_now = user32.GetForegroundWindow()
pid = wintypes.DWORD()
user32.GetWindowThreadProcessId(fg_now, ctypes.byref(pid))
title_buf = ctypes.create_unicode_buffer(512)
user32.GetWindowTextW(fg_now, title_buf, 512)
print(f"Foreground Window after click: {hex(fg_now)}, PID: {pid.value}, Title: '{title_buf.value}'")

if fg_now == hwnd or pid.value == 25576:
    print("🎉 SUCCESS! PoE2 IS FOREGROUND!")
else:
    print("Not foreground yet.")
