import ctypes, time, win32gui, win32process, psutil
from PIL import ImageGrab

user32 = ctypes.windll.user32
shell32 = ctypes.windll.shell32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk: user32.SetThreadDesktop(hdesk)

print("Launching AutoUpdateVCTK.exe via ShellExecuteW...")
shell32.ShellExecuteW(
    None,
    "runas",
    r"C:\JXVCTK\JxVoCongTruyenKy\AutoUpdateVCTK.exe",
    None,
    r"C:\JXVCTK\JxVoCongTruyenKy",
    1
)

time.sleep(3.0)

launcher_hwnd = None
for _ in range(10):
    def cb(h, _):
        global launcher_hwnd
        if win32gui.IsWindowVisible(h):
            _, pid = win32process.GetWindowThreadProcessId(h)
            try:
                pname = psutil.Process(pid).name().lower()
                if "autoupdate" in pname:
                    launcher_hwnd = h
            except Exception:
                pass
    win32gui.EnumWindows(cb, None)
    if launcher_hwnd:
        break
    time.sleep(1.0)

with open(r"c:\Projects\JX\logs\launcher_dump.txt", "w", encoding="utf-8") as f:
    f.write(f"Launcher HWND: {hex(launcher_hwnd) if launcher_hwnd else 'None'}\n")
    if launcher_hwnd:
        f.write(f"Class: {win32gui.GetClassName(launcher_hwnd)}, Title: '{win32gui.GetWindowText(launcher_hwnd)}'\n")
        rect = win32gui.GetWindowRect(launcher_hwnd)
        f.write(f"Rect: {rect}\n")
        img = ImageGrab.grab(bbox=rect, all_screens=True)
        img.save(r"c:\Projects\JX\logs\launcher_dump.png")
        
        def c_cb(ch, _):
            cid = user32.GetDlgCtrlID(ch)
            cls = win32gui.GetClassName(ch)
            txt = win32gui.GetWindowText(ch)
            crect = win32gui.GetWindowRect(ch)
            vis = win32gui.IsWindowVisible(ch)
            f.write(f"  Child: HWND 0x{ch:X}, ID {cid}, Class '{cls}', Vis {vis}, Rect {crect}, Text '{txt}'\n")
        win32gui.EnumChildWindows(launcher_hwnd, c_cb, None)
