import time
import sys
import ctypes
from ctypes import wintypes
import uiautomation as auto
from PIL import ImageGrab
import win32gui

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

hwnds = []
def enum_cb(hwnd, _):
    txt_len = user32.GetWindowTextLengthW(hwnd) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(hwnd, txt_buf, txt_len)
    if "JXHelper" in txt_buf.value and user32.IsWindowVisible(hwnd):
        hwnds.append(hwnd)
    return True

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

if not hwnds:
    print("JXHelper window not found via EnumWindows!")
    sys.exit(1)

main_hwnd = hwnds[0]
print(f"Connecting to HWND: {hex(main_hwnd)}")
win = auto.ControlFromHandle(main_hwnd)
print(f"Found Window: '{win.Name}', ControlType: {win.ControlTypeName}")

# Find ListView
lvw = win.ListControl()
if lvw.Exists(0, 0):
    print(f"Found ListControl: {lvw.Name}")
    items = lvw.GetChildren()
    print(f"List items count: {len(items)}")
    for i, it in enumerate(items):
        print(f"  Item {i}: '{it.Name}'")

# Look for ComboBoxes
combos = []
for c, depth in auto.WalkControl(win):
    if c.ControlType == auto.ControlType.ComboBoxControl:
        combos.append(c)
        print(f"Found ComboBox: Name='{c.Name}', AutomationId='{c.AutomationId}', Rect={c.BoundingRectangle}")

# Identify Sect ComboBox: it is located around x: 72, y: 146 relative to window
# Let's inspect bounding rectangles relative to window rect
w_rect = win32gui.GetWindowRect(main_hwnd)
print(f"Window Rect: {w_rect}")
for c in combos:
    cr = c.BoundingRectangle
    rx = cr.left - w_rect[0]
    ry = cr.top - w_rect[1]
    print(f"Combo relative: ({rx}, {ry}), width={cr.width()}, height={cr.height()}")
