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

sys.stdout.reconfigure(encoding='utf-8')

main_hwnd = 0x48b12a8
win = auto.ControlFromHandle(main_hwnd)
print("Connected to:", win.Name)

# Find all ComboBox controls
combos = win.GetChildren()
print("Direct children of window:")
for c in combos:
    print(f" - {c.Name} ({c.ControlTypeName}) AutomationId={c.AutomationId}")

# Walk to find cboSect
sect_combo = None
for c, depth in auto.WalkControl(win):
    if c.ControlType == auto.ControlType.ComboBoxControl:
        print(f"Found ComboBox: Name='{c.Name}', AutomationId='{c.AutomationId}', Rect={c.BoundingRectangle}")
        if c.AutomationId == "cboSect":
            sect_combo = c
            break

if not sect_combo:
    # Try finding by rect (width ~ 130)
    for c, depth in auto.WalkControl(win):
        if c.ControlType == auto.ControlType.ComboBoxControl and c.BoundingRectangle.width() == 130:
            sect_combo = c
            print(f"Found sect_combo by width 130: {c.AutomationId}")
            break

if sect_combo:
    print(f"==> Target Sect Combo found: {sect_combo.AutomationId}")
    # Check current value
    val_pat = sect_combo.GetPattern(auto.PatternId.ValuePattern)
    if val_pat:
        print(f"Current Value: {val_pat.Value}")
        val_pat.SetValue("Võ Đang")
        print("Set value to Võ Đang via ValuePattern!")
    else:
        # Expand and select
        exp_pat = sect_combo.GetPattern(auto.PatternId.ExpandCollapsePattern)
        if exp_pat:
            print("Expanding combo...")
            exp_pat.Expand()
            time.sleep(0.5)
            # Find list item 'Võ Đang'
            vodang_item = sect_combo.ListItemControl(Name="Võ Đang")
            if vodang_item.Exists(1, 0):
                print("Found Võ Đang item! Selecting...")
                sel_pat = vodang_item.GetPattern(auto.PatternId.SelectionItemPattern)
                if sel_pat:
                    sel_pat.Select()
                else:
                    vodang_item.Click()
            exp_pat.Collapse()

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_uiauto_result.png"
img.save(out)
print(f"Saved {out}")
