import sys, os, time, subprocess, ctypes
import win32gui, win32process, psutil
from PIL import ImageGrab
sys.stdout.reconfigure(encoding='utf-8')

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

# Check if any autoupdate is running
for p in psutil.process_iter(['pid', 'name']):
    if p.info['name'] and 'autoupdate' in p.info['name'].lower():
        print(f"Killing old AutoUpdate: PID {p.info['pid']}")
        try: p.kill()
        except: pass
time.sleep(1)

print("Starting AutoUpdateVCTK.exe via ShellExecuteW 'open'...")
res = shell32.ShellExecuteW(None, "open", r"C:\JXVCTK\JxVoCongTruyenKy\AutoUpdateVCTK.exe", None, r"C:\JXVCTK\JxVoCongTruyenKy", 1)
print(f"ShellExecuteW 'open' returned: {res}")

# Check for 15 seconds
launcher_hwnd = None
modal_hwnd = None
start_t = time.time()
while time.time() - start_t < 15:
    time.sleep(1.0)
    for p in psutil.process_iter(['pid', 'name']):
        if p.info['name'] and 'autoupdate' in p.info['name'].lower():
            print(f"AutoUpdate process active: PID {p.info['pid']}")
    
    def cb(h, _):
        global launcher_hwnd, modal_hwnd
        if win32gui.IsWindowVisible(h):
            cls = win32gui.GetClassName(h)
            txt = win32gui.GetWindowText(h)
            _, pid = win32process.GetWindowThreadProcessId(h)
            try:
                pname = psutil.Process(pid).name().lower()
                if "autoupdate" in pname:
                    print(f"  Found window: HWND 0x{h:X}, Class: {cls}, Title: '{txt}'")
                    if txt == "Mở Auto":
                        modal_hwnd = h
                    else:
                        launcher_hwnd = h
            except Exception:
                pass
    win32gui.EnumWindows(cb, None)
    if launcher_hwnd:
        break

if launcher_hwnd:
    rect = win32gui.GetWindowRect(launcher_hwnd)
    print(f"Launcher HWND: 0x{launcher_hwnd:X}, Rect: {rect}")
    img = ImageGrab.grab(bbox=rect, all_screens=True)
    img.save(r"C:\Projects\JX\logs\launcher_test_open.png")
    print("Saved launcher_test_open.png")
else:
    print("No launcher window found!")
