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

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

launcher_hwnd = None
modal_hwnd = None

def enum_cb(h, _):
    global launcher_hwnd, modal_hwnd
    if win32gui.IsWindowVisible(h):
        txt = win32gui.GetWindowText(h)
        cls = win32gui.GetClassName(h)
        _, pid = win32process.GetWindowThreadProcessId(h)
        try:
            pname = psutil.Process(pid).name().lower()
            if "autoupdate" in pname:
                print(f"AutoUpdate window: HWND 0x{h:X}, Class: '{cls}', Title: '{txt}'")
                if "mở auto" in txt.lower() or cls == "#32770" and txt == "Mở Auto":
                    modal_hwnd = h
                else:
                    launcher_hwnd = h
        except Exception:
            pass

win32gui.EnumWindows(enum_cb, None)

if modal_hwnd:
    print(f"Closing modal popup 0x{modal_hwnd:X}...")
    user32.PostMessageW(modal_hwnd, 0x0010, 0, 0) # WM_CLOSE
    time.sleep(1.0)

# Check launcher hwnd
if launcher_hwnd:
    print(f"Found launcher: 0x{launcher_hwnd:X}")
    btn_start = user32.GetDlgItem(launcher_hwnd, 1404)
    print(f"Button 1404: 0x{btn_start:X}")
    if btn_start:
        user32.PostMessageW(btn_start, 0x00F5, 0, 0) # BM_CLICK
        time.sleep(0.1)
        user32.PostMessageW(launcher_hwnd, 0x0111, 1404, btn_start)
        print("Clicked 'Bắt đầu'!")
