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)

# Find JXHelper window
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
WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.EnumWindows(WNDENUMPROC(cb), 0)

main_hwnd = hwnds[0]
print(f"Main HWND: {hex(main_hwnd)}")

controls = []
def enum_child(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    if "SysListView32" in cls_buf.value:
        controls.append(h)
    return True
user32.EnumChildWindows(main_hwnd, WNDENUMPROC(enum_child), 0)
lvw = controls[0]

WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
MK_LBUTTON = 0x0001
def make_lparam(x, y):
    return (y << 16) | (x & 0xFFFF)

rect = win32gui.GetWindowRect(main_hwnd)

# 1. Click Item 1 (BoCuaCacCon) at y = 55
print("Clicking Item 1 (BoCuaCacCon) at (50, 55)...")
user32.PostMessageW(lvw, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(50, 55))
user32.PostMessageW(lvw, WM_LBUTTONUP, 0, make_lparam(50, 55))
time.sleep(1)

img1 = ImageGrab.grab(bbox=rect)
out1 = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\test_item1_bocuacaccon.png"
img1.save(out1)
print(f"Saved: {out1}")

# 2. Click Item 2 (ConGailCung) at y = 75
print("Clicking Item 2 (ConGailCung) at (50, 75)...")
user32.PostMessageW(lvw, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(50, 75))
user32.PostMessageW(lvw, WM_LBUTTONUP, 0, make_lparam(50, 75))
time.sleep(1)

img2 = ImageGrab.grab(bbox=rect)
out2 = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\test_item2_congailcung.png"
img2.save(out2)
print(f"Saved: {out2}")

# 3. Click Item 0 (ConCuaBoMe) at y = 35
print("Clicking Item 0 (ConCuaBoMe) at (50, 35)...")
user32.PostMessageW(lvw, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(50, 35))
user32.PostMessageW(lvw, WM_LBUTTONUP, 0, make_lparam(50, 35))
time.sleep(1)

img0 = ImageGrab.grab(bbox=rect)
out0 = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\test_item0_concuabome.png"
img0.save(out0)
print(f"Saved: {out0}")
