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

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

def get_sword3_windows():
    wins = []
    def cb(h, _):
        if win32gui.GetClassName(h) == "Sword3 Class":
            _, pid = win32process.GetWindowThreadProcessId(h)
            wins.append((h, pid))
    win32gui.EnumWindows(cb, None)
    return wins

existing_hwnds = {h for h, _ in get_sword3_windows()}
print(f"Existing Sword3 HWNDs: {[hex(h) for h in existing_hwnds]}")

# 1. Check if AutoUpdateVCTK is running, if not start it
launcher_proc = None
for p in psutil.process_iter(['name', 'pid']):
    if "autoupdate" in p.info['name'].lower():
        launcher_proc = p
        break

if not launcher_proc:
    print("Launching AutoUpdateVCTK.exe...")
    os.startfile(r"C:\JXVCTK\JxVoCongTruyenKy\AutoUpdateVCTK.exe")
    time.sleep(3.0)

# 2. Find launcher window
launcher_hwnd = None
for attempt in range(15):
    def lcb(h, _):
        global launcher_hwnd
        if win32gui.IsWindowVisible(h):
            cls = win32gui.GetClassName(h)
            title = win32gui.GetWindowText(h)
            if "autoupdate" in title.lower() or "võ công" in title.lower() or cls == "#32770":
                _, pid = win32process.GetWindowThreadProcessId(h)
                try:
                    pname = psutil.Process(pid).name().lower()
                    if "autoupdate" in pname:
                        launcher_hwnd = h
                except Exception:
                    pass
    win32gui.EnumWindows(lcb, 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:
    print("Could not find launcher window!")
    exit(1)

# 3. Find button 1404 and click it
btn_start = user32.GetDlgItem(launcher_hwnd, 1404)
print(f"Button 1404 HWND: {hex(btn_start) if btn_start else 'None'}")
if btn_start:
    user32.PostMessageW(btn_start, 0x00F5, 0, 0) # BM_CLICK
else:
    # Try searching children
    def child_cb(ch, _):
        cid = user32.GetDlgCtrlID(ch)
        txt = win32gui.GetWindowText(ch)
        if cid == 1404 or "bắt đầu" in txt.lower():
            user32.PostMessageW(ch, 0x00F5, 0, 0)
    win32gui.EnumChildWindows(launcher_hwnd, child_cb, None)

print("Clicked 'Bắt đầu' on launcher, waiting for new Sword3 Class window...")

# 4. Wait for new Sword3 Class window
new_hwnd = None
new_pid = None
for _ in range(30):
    time.sleep(1.0)
    current_wins = get_sword3_windows()
    for h, p in current_wins:
        if h not in existing_hwnds:
            new_hwnd = h
            new_pid = p
            break
    if new_hwnd:
        break

if not new_hwnd:
    print("No new Sword3 window detected!")
    exit(1)

print(f"Detected new game window: HWND {hex(new_hwnd)}, PID {new_pid}!")
with open(r"c:\Projects\JX\logs\new_game_hwnd.txt", "w") as f:
    f.write(f"{new_hwnd},{new_pid}\n")
