import sys

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

import ctypes

import uiautomation as auto
import win32con
import win32gui
import win32service

h_desk = win32service.OpenDesktop("Default", 0, False, win32con.GENERIC_ALL)
ctypes.windll.user32.SetThreadDesktop(int(h_desk))

# Find HWND by title
target_hwnd = 0
def enum_cb(h, _):
    global target_hwnd
    if win32gui.IsWindowVisible(h):
        t = win32gui.GetWindowText(h)
        if "Discord" in t:
            target_hwnd = h

win32gui.EnumDesktopWindows(int(h_desk), enum_cb, None)
print(f"Target HWND: {target_hwnd} ('{win32gui.GetWindowText(target_hwnd)}')")

if target_hwnd:
    ctrl = auto.ControlFromHandle(target_hwnd)
    print(f"Control from handle: {ctrl}")
    if ctrl:
        print(f"Name: {ctrl.Name}, ClassName: {ctrl.ClassName}")
        # Walk through children
        count = 0
        for child, depth in auto.WalkTree(ctrl, maxDepth=8):
            if child.Name:
                print(f"[{depth}] {child.ControlTypeName}: {repr(child.Name[:80])}")
                count += 1
                if count >= 30:
                    break
        print(f"Total elements printed: {count}")
