import ctypes
import sys
from ctypes import wintypes
import win32gui
import win32process
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)

hwnds = []

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

def enum_cb(hwnd, lparam):
    _, pid = win32process.GetWindowThreadProcessId(hwnd)
    txt_len = user32.GetWindowTextLengthW(hwnd) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(hwnd, txt_buf, txt_len)
    title = txt_buf.value
    
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(hwnd, cls_buf, 256)
    cls = cls_buf.value
    
    if pid in target_pids or "JXHelper" in title:
        hwnds.append((hwnd, pid, cls, title, user32.IsWindowVisible(hwnd)))
    return True

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.EnumWindows(WNDENUMPROC(enum_cb), 0)

print(f"Found {len(hwnds)} windows:")
for h, pid, cls, title, vis in hwnds:
    print(f"HWND: {hex(h)}, PID: {pid}, Class: {cls}, Title: '{title}', Visible: {vis}")
    rect = win32gui.GetWindowRect(h)
    print(f"Rect: {rect}")
    if rect[2] > rect[0] and rect[3] > rect[1]:
        img = ImageGrab.grab(bbox=rect)
        out1 = r"c:\Projects\JX\logs\jxhelper_per_char_sect_live.png"
        out2 = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\jxhelper_per_char_sect_live.png"
        img.save(out1)
        img.save(out2)
        print(f"Captured screenshot to {out1} and {out2}")
