import ctypes
import sys
import time
from ctypes import wintypes
import win32gui
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)

hwnds = []
def cb(h, _):
    txt_len = user32.GetWindowTextLengthW(h) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, txt_buf, txt_len)
    if "JXHelper" in txt_buf.value and user32.IsWindowVisible(h):
        hwnds.append(h)
    return True
user32.EnumWindows(ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(cb), 0)

main_hwnd = hwnds[0]
children = []
def child_cb(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    children.append((h, cls_buf.value))
    return True
user32.EnumChildWindows(main_hwnd, ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(child_cb), 0)

lvw = next(h for h, cls in children if "SysListView32" in cls)
print(f"ListView: {hex(lvw)}")

WM_SETFOCUS = 0x0007
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101
VK_DOWN = 0x28

print("Sending SetFocus and VK_DOWN to ListView...")
user32.PostMessageW(lvw, WM_SETFOCUS, 0, 0)
time.sleep(0.2)
user32.PostMessageW(lvw, WM_KEYDOWN, VK_DOWN, 0)
user32.PostMessageW(lvw, WM_KEYUP, VK_DOWN, 0)
time.sleep(1)

rect = win32gui.GetWindowRect(main_hwnd)
img = ImageGrab.grab(bbox=rect)
out = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\test_vk_down_selection.png"
img.save(out)
print(f"Saved {out}")
