import win32gui
import win32process
import ctypes
from ctypes import wintypes
import sys
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)

# TCVN3 Decoder
TCVN3_MAP = {
    0xb8: 'á', 0xb5: 'à', 0xb7: 'ả', 0xb6: 'ã', 0xb9: 'ạ',
    0xca: 'ă', 0xbe: 'ắ', 0xbb: 'ằ', 0xbd: 'ẳ', 0xbc: 'ẵ', 0xc6: 'ặ',
    0xcb: 'â', 0xc1: 'ấ', 0xbf: 'ầ', 0xc0: 'ẩ', 0xc2: 'ẫ', 0xc5: 'ậ',
    0xd0: 'é', 0xcd: 'è', 0xcf: 'ẻ', 0xce: 'ẽ', 0xd1: 'ẹ',
    0xd2: 'ê', 0xd5: 'ế', 0xd3: 'ề', 0xd4: 'ể', 0xd6: 'ễ', 0xd8: 'ệ',
    0xdc: 'í', 0xd9: 'ì', 0xdb: 'ỉ', 0xda: 'ĩ', 0xdd: 'ị',
    0xf3: 'ó', 0xdf: 'ò', 0xee: 'ỏ', 0xde: 'õ', 0xf4: 'ọ',
    0xf5: 'ô', 0xf8: 'ố', 0xf6: 'ồ', 0xf7: 'ổ', 0xf9: 'ỗ', 0xfa: 'ộ',
    0xfb: 'ơ', 0xfe: 'ớ', 0xfc: 'ờ', 0xfd: 'ở', 0xff: 'ỡ', 0x82: 'ợ',
    0x87: 'ú', 0x83: 'ù', 0x85: 'ủ', 0x84: 'ũ', 0x88: 'ụ',
    0x89: 'ư', 0x8c: 'ứ', 0x8a: 'ừ', 0x8b: 'ử', 0x8d: 'ữ', 0x8e: 'ự',
    0x95: 'ý', 0x90: 'ỳ', 0x93: 'ỷ', 0x92: 'ỹ', 0x96: 'ỵ',
    0xa7: 'đ', 0xa1: 'Đ'
}

def decode_tcvn3(s_bytes):
    chars = []
    for b in s_bytes:
        if b in TCVN3_MAP:
            chars.append(TCVN3_MAP[b])
        elif 32 <= b <= 126:
            chars.append(chr(b))
        elif b == 0:
            break
        else:
            chars.append(f"\\x{b:02x}")
    return "".join(chars)

def decode_str(s):
    # s is str from win32gui (treated as latin1 codepoints)
    b = s.encode('latin1', errors='replace')
    return decode_tcvn3(b)

h_buff = 0x2bb0eb0
print(f"=== Inspecting Window {hex(h_buff)}: {win32gui.GetWindowText(h_buff)} ===")
rect = win32gui.GetWindowRect(h_buff)
print(f"Window Rect: {rect}")
img = ImageGrab.grab(bbox=rect)
out_img = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\vlbs_chieu_thuc_ho_tro_window.png"
img.save(out_img)
print(f"Saved screenshot to {out_img}")

children = []
def cb(h, _):
    cls = win32gui.GetClassName(h)
    raw_txt = win32gui.GetWindowText(h)
    decoded = decode_str(raw_txt) if raw_txt else ""
    r = win32gui.GetWindowRect(h)
    rel = (r[0] - rect[0], r[1] - rect[1], r[2] - r[0], r[3] - r[1])
    is_check = user32.SendMessageW(h, 0x00F0, 0, 0) # BM_GETCHECK
    children.append((h, cls, decoded, rel, is_check))
    return True

user32.EnumChildWindows(h_buff, ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(cb), 0)

for h, cls, txt, rel, check in children:
    chk_str = f" [Checked={check}]" if "button" in cls.lower() and check in [0, 1] else ""
    val_str = f" '{txt}'" if txt else ""
    print(f"{hex(h)} [{cls}] rel={rel}:{val_str}{chk_str}")
