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)

# Kill any existing AutoUpdateVCTK
for p in psutil.process_iter(['name']):
    if p.info['name'] and 'autoupdate' in p.info['name'].lower():
        try: p.kill()
        except: pass
time.sleep(1.0)

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

launcher_hwnd = None
start_t = time.time()
print("Waiting for AutoUpdateVCTK window (up to 30s)...")
while time.time() - start_t < 30:
    time.sleep(1.0)
    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:
                    cls = win32gui.GetClassName(h)
                    txt = win32gui.GetWindowText(h)
                    print(f"  Found window: HWND 0x{h:X}, Class: {cls}, Title: '{txt}'")
                    launcher_hwnd = h
            except Exception:
                pass
    win32gui.EnumWindows(cb, None)
    if launcher_hwnd:
        break

with open(r"c:\Projects\JX\logs\wait_launcher.txt", "w", encoding="utf-8") as f:
    f.write(f"Launcher HWND: {hex(launcher_hwnd) if launcher_hwnd else 'None'}\n")
    if launcher_hwnd:
        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_waited.png")
        f.write("Saved launcher_waited.png\n")
