import ctypes
import sys
import time
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)

wins = []
def cb(h, _):
    if not user32.IsWindowVisible(h):
        return True
    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
    try:
        pname = psutil.Process(pid.value).name().lower()
    except Exception:
        pname = ''
    if any(k in pname for k in ['game', 'vggame']):
        length = user32.GetWindowTextLengthW(h)
        buf = ctypes.create_unicode_buffer(length + 1)
        user32.GetWindowTextW(h, buf, length + 1)
        cls_buf = ctypes.create_unicode_buffer(256)
        user32.GetClassNameW(h, cls_buf, 256)
        rect = win32gui.GetWindowRect(h)
        wins.append((h, pid.value, pname, cls_buf.value, buf.value, rect))
    return True

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

print(f"Found {len(wins)} game windows:")
for h, pid, pname, cls, title, r in wins:
    print(f"HWND: 0x{h:X} | PID: {pid} ({pname}) | Class: {cls} | Title: '{title}' | Rect: {r}")
    if r[2] > r[0] and r[3] > r[1]:
        img = ImageGrab.grab(bbox=r)
        save_path = fr"C:\Projects\JX\logs\game_live_{pid}.png"
        img.save(save_path)
        print(f"Saved screenshot to {save_path}")
