import ctypes, time
from ctypes import wintypes
import win32gui
from PIL import ImageGrab

user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk:
    user32.SetThreadDesktop(hdesk)

target_pid = 42272
game_hwnd = None

def cb(h, _):
    global game_hwnd
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    if cls_buf.value == 'Sword3 Class':
        pid = wintypes.DWORD()
        user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
        if pid.value == target_pid:
            game_hwnd = h
    return True

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

if game_hwnd:
    # Bring to foreground or ensure visible
    rect = win32gui.GetWindowRect(game_hwnd)
    print(f"Game HWND: {hex(game_hwnd)}, Rect: {rect}")
    # Capture bounding box
    img = ImageGrab.grab(bbox=rect)
    save_path = r'c:\Projects\JX\logs\game_live_view.png'
    img.save(save_path)
    print(f"Saved live screenshot to {save_path}")
else:
    print("Game window not found!")
