import os
import sys
import time
import win32api
import win32gui
import ctypes
from ctypes import wintypes
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"Launching {exe_path} via ShellExecute...")
res = win32api.ShellExecute(0, "open", exe_path, "", work_dir, 1)
print(f"ShellExecute result: {res}")

time.sleep(3)

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)
    if "JXHelper" in txt_buf.value and user32.IsWindowVisible(h):
        hwnds.append((h, txt_buf.value))
    return True

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

print(f"Found {len(hwnds)} JXHelper windows on desktop:")
for h, title in hwnds:
    rect = win32gui.GetWindowRect(h)
    print(f"HWND: {hex(h)}, Title: '{title}', Rect: {rect}")
    if rect[2] > rect[0] and rect[3] > rect[1]:
        img = ImageGrab.grab(bbox=rect)
        out = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\jxhelper_support_live.png"
        img.save(out)
        print(f"Saved screenshot to {out}")
