import ctypes
import sys
import time
from ctypes import wintypes
import win32gui
import win32con
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 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!")
    sys.exit(1)

main_hwnd = hwnds[0]
controls = []
def enum_child(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    controls.append((h, cls_buf.value))
    return True

user32.EnumChildWindows(main_hwnd, WNDENUMPROC(enum_child), 0)

CB_GETCOUNT = 0x0146
CB_GETLBTEXT = 0x0148
CB_GETLBTEXTLEN = 0x0149
CB_GETCURSEL = 0x0147
CB_SETCURSEL = 0x014E
CBN_SELCHANGE = 1
WM_COMMAND = 0x0111

combos = []
for h, cls in controls:
    if "ComboBox" in cls:
        count = user32.SendMessageW(h, CB_GETCOUNT, 0, 0)
        items = []
        for i in range(count):
            tlen = user32.SendMessageW(h, CB_GETLBTEXTLEN, i, 0)
            tbuf = ctypes.create_unicode_buffer(tlen + 1)
            user32.SendMessageW(h, CB_GETLBTEXT, i, ctypes.byref(tbuf))
            items.append(tbuf.value)
        cur = user32.SendMessageW(h, CB_GETCURSEL, 0, 0)
        cur_text = items[cur] if 0 <= cur < len(items) else "None"
        combos.append((h, cur_text, items))
        print(f"ComboBox {hex(h)}: CurSel={cur} ('{cur_text}'), Items={items[:4]}... Total={len(items)}")

# Find Sect combo
sect_combo = None
for h, cur_text, items in combos:
    if "Võ Đang" in items and "Cái Bang" in items:
        sect_combo = h
        print(f"\n=> FOUND SECT COMBOBOX: {hex(h)} currently selected: '{cur_text}'")
        break

# Find ListView
lvw = next((h for h, cls in controls if "SysListView32" in cls), None)
print(f"=> ListView: {hex(lvw)}")

# Test changing Sect to Võ Đang (index 1) for current account
if sect_combo:
    # Set to Võ Đang (index 1)
    user32.SendMessageW(sect_combo, CB_SETCURSEL, 1, 0)
    # Notify parent
    ctrl_id = user32.GetDlgCtrlID(sect_combo)
    user32.SendMessageW(user32.GetParent(sect_combo), WM_COMMAND, (CBN_SELCHANGE << 16) | (ctrl_id & 0xFFFF), sect_combo)
    print("Changed sect to Võ Đang and sent CBN_SELCHANGE!")

time.sleep(1)

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