import ctypes, sys
from ctypes import wintypes
import win32gui, win32con, time
from PIL import ImageGrab

sys.stdout.reconfigure(encoding='utf-8')
user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk: user32.SetThreadDesktop(hdesk)

btn_h = 0x27c0636
rect = win32gui.GetWindowRect(btn_h)
print(f'Button rect: {rect}')

# Let us click right in the center of the button using PostMessage or mouse_event / SetCursorPos in desktop thread
cx = (rect[0] + rect[2]) // 2
cy = (rect[1] + rect[3]) // 2

# Bring AutoVLBS to foreground
win32gui.SetForegroundWindow(0x8c4c02)
time.sleep(0.2)

# Click using PostMessage WM_LBUTTONDOWN / WM_LBUTTONUP directly to the button
lparam = ((cy - rect[1]) << 16) | (cx - rect[0])
win32gui.PostMessage(btn_h, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lparam)
time.sleep(0.05)
win32gui.PostMessage(btn_h, win32con.WM_LBUTTONUP, 0, lparam)
time.sleep(1.0)

# Now check if any new window appeared
def cb(h, _):
    if user32.IsWindowVisible(h):
        txt_len = user32.GetWindowTextLengthW(h) + 1
        buf = ctypes.create_unicode_buffer(txt_len)
        user32.GetWindowTextW(h, buf, txt_len)
        r = win32gui.GetWindowRect(h)
        pid = wintypes.DWORD()
        user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
        if pid.value == 38488:
            print(f'VLBS window: {hex(h)}, title="{buf.value}", rect={r}')
            if r != (1923, 413, 2142, 1024):
                img = ImageGrab.grab(bbox=r)
                img.save(r'C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\vlbs_dialog_popup.png')
                print('Captured popup dialog!')
    return True

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.EnumWindows(WNDENUMPROC(cb), 0)
