import ctypes, time, win32gui, win32process, psutil
from ctypes import wintypes

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

# Terminate any old AutoUpdate
for p in psutil.process_iter(['name', 'pid']):
    if "autoupdate" in p.info['name'].lower():
        p.kill()
time.sleep(1.0)

# Start AutoUpdateVCTK
print("Starting AutoUpdateVCTK.exe...")
import subprocess
subprocess.Popen([r"C:\JXVCTK\JxVoCongTruyenKy\AutoUpdateVCTK.exe"], cwd=r"C:\JXVCTK\JxVoCongTruyenKy")
time.sleep(2.5)

launcher_hwnd = None
for _ in range(10):
    def cb(h, _):
        global launcher_hwnd
        if win32gui.IsWindowVisible(h):
            _, pid = win32process.GetWindowThreadProcessId(h)
            try:
                if "autoupdate" in psutil.Process(pid).name().lower():
                    txt = win32gui.GetWindowText(h)
                    cls = win32gui.GetClassName(h)
                    if cls == "#32770" or "võ công" in txt.lower():
                        launcher_hwnd = h
            except Exception:
                pass
    win32gui.EnumWindows(cb, None)
    if launcher_hwnd:
        break
    time.sleep(0.5)

print(f"Launcher HWND: {hex(launcher_hwnd) if launcher_hwnd else 'None'}")
if not launcher_hwnd:
    exit(1)

with open(r"c:\Projects\JX\logs\launcher_controls.txt", "w", encoding="utf-8") as f:
    f.write(f"Launcher HWND: {hex(launcher_hwnd)}\n")
    def c_cb(ch, _):
        cid = user32.GetDlgCtrlID(ch)
        cls = win32gui.GetClassName(ch)
        txt = win32gui.GetWindowText(ch)
        rect = win32gui.GetWindowRect(ch)
        vis = win32gui.IsWindowVisible(ch)
        f.write(f"  Control: HWND 0x{ch:X}, ID {cid}, Class '{cls}', Text '{txt}', Rect {rect}, Vis {vis}\n")
    win32gui.EnumChildWindows(launcher_hwnd, c_cb, None)

print("Controls written to launcher_controls.txt")
