import ctypes
import sys
import time
from ctypes import wintypes
import win32gui
import win32con
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 all vggame processes
procs = [p for p in psutil.process_iter(['pid', 'name', 'create_time']) if 'vggame' in p.info['name'].lower()]
print(f"Found {len(procs)} vggame processes:")
for p in procs:
    print(f"PID: {p.info['pid']}, Created: {time.strftime('%H:%M:%S', time.localtime(p.info['create_time']))}")

# Find windows
wins = []
def cb(h, _):
    if not user32.IsWindowVisible(h):
        return True
    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
    for p in procs:
        if pid.value == p.info['pid']:
            cls_buf = ctypes.create_unicode_buffer(256)
            user32.GetClassNameW(h, cls_buf, 256)
            if cls_buf.value == "Sword3 Class":
                wins.append((h, pid.value))
    return True

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

print(f"\nFound {len(wins)} game windows:")
for i, (h, pid) in enumerate(wins):
    print(f"Window {i+1}: HWND 0x{h:X}, PID: {pid}")
    # Bring to foreground to capture accurately
    user32.ShowWindow(h, win32con.SW_RESTORE)
    user32.SetForegroundWindow(h)
    time.sleep(0.5)
    rect = win32gui.GetWindowRect(h)
    if rect[2] > rect[0] and rect[3] > rect[1]:
        img = ImageGrab.grab(bbox=rect)
        path = fr"C:\Projects\JX\logs\game_win_{pid}.png"
        img.save(path)
        print(f"Captured PID {pid} to {path}")

