import win32gui, win32process, psutil
from PIL import ImageGrab
import os

os.makedirs('c:/Projects/JX/logs', exist_ok=True)

def enum_cb(hwnd, _):
    if win32gui.IsWindowVisible(hwnd):
        _, pid = win32process.GetWindowThreadProcessId(hwnd)
        try:
            name = psutil.Process(pid).name()
        except Exception:
            name = ''
        if any(k in name.lower() for k in ['game', 'vggame', 'vctk', 'autoupdate']):
            title = win32gui.GetWindowText(hwnd)
            cls = win32gui.GetClassName(hwnd)
            rect = win32gui.GetWindowRect(hwnd)
            print(f'PID {pid} ({name}): HWND 0x{hwnd:X}, Class: {cls}, Title: "{title}", Rect: {rect}')
            if rect[2] > rect[0] and rect[3] > rect[1]:
                try:
                    shot = ImageGrab.grab(bbox=rect)
                    path = f'c:/Projects/JX/logs/proc_{pid}_{hwnd:X}.png'
                    shot.save(path)
                    print(f'  -> Saved {path}')
                except Exception as e:
                    print(f'  -> Error grabbing: {e}')
    return True

win32gui.EnumWindows(enum_cb, None)
