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

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

hwnds = []
def cb(h, _):
    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
    if pid.value in target_pids:
        cls_buf = ctypes.create_unicode_buffer(256)
        user32.GetClassNameW(h, cls_buf, 256)
        txt_len = user32.GetWindowTextLengthW(h) + 1
        txt_buf = ctypes.create_unicode_buffer(txt_len)
        user32.GetWindowTextW(h, txt_buf, txt_len)
        if user32.IsWindowVisible(h):
            hwnds.append((h, cls_buf.value, txt_buf.value))
    return True

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

for h, cls, txt in hwnds:
    print(f'Found HWND: {hex(h)}, Class: {cls}, Text: "{txt}"')
    rect = win32gui.GetWindowRect(h)
    print(f"Window Rect: {rect}, Width: {rect[2] - rect[0]}, Height: {rect[3] - rect[1]}")
    img = ImageGrab.grab(bbox=rect)
    save_path = r'c:\Projects\JX\logs\jxhelper_compact_ui.png'
    img.save(save_path)
    print(f"Saved {save_path}")

# Also capture full desktop overview
desk_img = ImageGrab.grab()
desk_path = r'c:\Projects\JX\logs\desktop_compact_overview.png'
desk_img.save(desk_path)
print(f"Saved {desk_path}")
