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

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

existing_pids = set(psutil.pids())

# Launch AutoUpdateVCTK if not running
proc = None
for p in psutil.process_iter(['name', 'pid']):
    if "autoupdate" in p.info['name'].lower():
        proc = p
        break

if not proc:
    print("Launching AutoUpdateVCTK.exe...")
    subprocess.Popen([r"C:\JXVCTK\JxVoCongTruyenKy\AutoUpdateVCTK.exe"], cwd=r"C:\JXVCTK\JxVoCongTruyenKy")
    time.sleep(3.0)

# Find launcher window
launcher_hwnd = None
for attempt in range(10):
    def cb(h, _):
        global launcher_hwnd
        if win32gui.IsWindowVisible(h):
            txt = win32gui.GetWindowText(h)
            _, pid = win32process.GetWindowThreadProcessId(h)
            try:
                pname = psutil.Process(pid).name().lower()
                if "autoupdate" in pname:
                    if txt == "Mở Auto":
                        user32.PostMessageW(h, 0x0010, 0, 0) # Close modal
                    elif "võ công" in txt.lower() or "trọn vẹn" in txt.lower() or not txt:
                        launcher_hwnd = h
            except Exception:
                pass
    win32gui.EnumWindows(cb, None)
    if launcher_hwnd:
        break
    time.sleep(1.0)

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

# Click "Bắt đầu" at (767, 554)
print("Clicking 'Bắt đầu' at (767, 554)...")
lp = ((554 & 0xFFFF) << 16) | (767 & 0xFFFF)
user32.PostMessageW(launcher_hwnd, 0x0200, 0, lp)
time.sleep(0.05)
user32.PostMessageW(launcher_hwnd, 0x0201, 1, lp)
time.sleep(0.08)
user32.PostMessageW(launcher_hwnd, 0x0202, 0, lp)
time.sleep(0.05)

print("Waiting for new game process...")
new_pid = None
for _ in range(15):
    time.sleep(1.0)
    for p in psutil.process_iter(['name', 'pid']):
        if p.info['name'].lower() in ('vggame.exe', 'game.exe') and p.info['pid'] not in existing_pids:
            new_pid = p.info['pid']
            break
    if new_pid:
        break

print(f"New game process PID: {new_pid}")
