import os
import sys
import time
import subprocess
import ctypes
from ctypes import wintypes
import psutil
from PIL import ImageGrab

sys.stdout.reconfigure(encoding='utf-8')
user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk:
    user32.SetThreadDesktop(hdesk)

exe_path = r"C:\Projects\JX\runtime\JXHelper_Runtime.exe"
work_dir = r"C:\Projects\JX\runtime"

print(f"=== KHỞI CHẠY GUI JXHELPER LIVE ===")
# Dừng các tiến trình cũ
for p in psutil.process_iter(['pid', 'name']):
    if 'jxhelper' in (p.info['name'] or '').lower():
        try: p.kill()
        except: pass

time.sleep(1)

# Khởi chạy không block console
DETACHED_PROCESS = 0x00000008
CREATE_NEW_PROCESS_GROUP = 0x00000200
proc = subprocess.Popen(
    [exe_path, "--no-elevate"],
    cwd=work_dir,
    creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,
    close_fds=True
)
print(f"Đã kích hoạt process JXHelper: PID {proc.pid}")

time.sleep(3)

# Kiểm tra xem process còn sống không
active_pids = [p.pid for p in psutil.process_iter(['pid', 'name']) if 'jxhelper' in (p.info['name'] or '').lower()]
print(f"Các PID JXHelper đang chạy trên Windows: {active_pids}")

# Dò tìm cửa sổ GUI
hwnds = []
def cb(h, _):
    txt_len = user32.GetWindowTextLengthW(h) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, txt_buf, txt_len)
    title = txt_buf.value
    if "JXHelper" in title:
        hwnds.append((h, title, user32.IsWindowVisible(h)))
    return True

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.EnumDesktopWindows(hdesk, WNDENUMPROC(cb), 0)

print(f"Tìm thấy {len(hwnds)} cửa sổ JXHelper trên màn hình:")
for h, title, vis in hwnds:
    import win32gui
    rect = win32gui.GetWindowRect(h)
    print(f"  * HWND: {hex(h)} | Title: '{title}' | Visible: {vis} | Rect: {rect}")
    if vis and rect[2] > rect[0] and rect[3] > rect[1]:
        img = ImageGrab.grab(bbox=rect)
        out1 = r"c:\Projects\JX\logs\jxhelper_live_running_gui.png"
        out2 = r"C:\Users\Admin\.gemini\antigravity\brain\1b4a0d01-a767-4d3f-966f-116a863fc8de\jxhelper_live_running_gui.png"
        img.save(out1)
        img.save(out2)
        print(f"  -> Đã chụp ảnh giao diện thực tế vào: {out1}")

print("=== HOÀN TẤT KIỂM THỬ KHỞI ĐỘNG ===")
