import ctypes
from ctypes import wintypes
import win32gui
import win32process
import psutil
from PIL import ImageGrab

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

pids = [p.pid for p in psutil.process_iter(['pid', 'name']) if 'JXHelper' in (p.info['name'] or '')]
print(f"JXHelper PIDs: {pids}")

hwnds = []

for pid in pids:
    try:
        proc = psutil.Process(pid)
        threads = [t.id for t in proc.threads()]
        print(f"PID {pid} threads: {threads}")
        
        def thread_cb(h, _):
            length = user32.GetWindowTextLengthW(h) + 1
            buff = ctypes.create_unicode_buffer(length)
            user32.GetWindowTextW(h, buff, length)
            cls_buf = ctypes.create_unicode_buffer(256)
            user32.GetClassNameW(h, cls_buf, 256)
            vis = user32.IsWindowVisible(h)
            hwnds.append((h, pid, cls_buf.value, buff.value, vis))
            return True

        WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
        for tid in threads:
            user32.EnumThreadWindows(tid, WNDENUMPROC(thread_cb), 0)
    except Exception as ex:
        print(f"Error inspecting pid {pid}: {ex}")

print(f"Found {len(hwnds)} windows:")
for h, pid, cls, title, vis in hwnds:
    print(f"HWND: {hex(h)}, Class: {cls}, Title: '{title}', Visible: {vis}")
    rect = win32gui.GetWindowRect(h)
    print(f"Rect: {rect}")
    if rect[2] > rect[0] and rect[3] > rect[1] and vis:
        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}")
