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

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

existing_pids = {p.pid for p in psutil.process_iter(['name']) if p.info['name'] and 'vggame' in p.info['name'].lower()}
print(f"Existing vggame PIDs: {existing_pids}")

existing_hwnds = []
def enum_cb(h, _):
    if win32gui.GetClassName(h) == "Sword3 Class":
        existing_hwnds.append(h)
win32gui.EnumWindows(enum_cb, None)
print(f"Existing Sword3 HWNDs: {[hex(h) for h in existing_hwnds]}")

# Launch Game.exe via ShellExecuteW 'runas'
print("Launching Game.exe with 'runas'...")
res = shell32.ShellExecuteW(
    None,
    "runas",
    r"C:\JXVCTK\JxVoCongTruyenKy\Game.exe",
    None,
    r"C:\JXVCTK\JxVoCongTruyenKy",
    1 # SW_SHOWNORMAL
)
print(f"ShellExecuteW returned: {res} (res > 32 means success)")

# Wait up to 35 seconds for new vggame / Sword3 window
new_hwnd = None
new_pid = None
start_t = time.time()
while time.time() - start_t < 35:
    time.sleep(1.5)
    # Check processes
    current_pids = {p.pid for p in psutil.process_iter(['name']) if p.info['name'] and 'vggame' in p.info['name'].lower()}
    diff_pids = current_pids - existing_pids
    if diff_pids:
        print(f"[{int(time.time() - start_t)}s] Detected new vggame PID: {diff_pids}")
    
    # Check windows
    current_hwnds = []
    def wcb(h, _):
        if win32gui.GetClassName(h) == "Sword3 Class":
            current_hwnds.append(h)
    win32gui.EnumWindows(wcb, None)
    diff_hwnds = set(current_hwnds) - set(existing_hwnds)
    if diff_hwnds:
        new_hwnd = list(diff_hwnds)[0]
        _, new_pid = win32process.GetWindowThreadProcessId(new_hwnd)
        print(f"[{int(time.time() - start_t)}s] SUCCESS! Detected new Sword3 window: HWND {hex(new_hwnd)}, PID {new_pid}")
        break

with open(r"c:\Projects\JX\logs\launch_test_out.txt", "w", encoding="utf-8") as f:
    f.write(f"ShellExecute result: {res}\n")
    f.write(f"New HWND: {hex(new_hwnd) if new_hwnd else 'None'}\n")
    f.write(f"New PID: {new_pid}\n")

if new_hwnd:
    rect = win32gui.GetWindowRect(new_hwnd)
    img = ImageGrab.grab(bbox=rect, all_screens=True)
    img.save(r"c:\Projects\JX\logs\new_game_screen.png")
    print("Saved new_game_screen.png")
