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

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

out_file = r"c:\Projects\JX\logs\real_windows_debug.txt"
f = open(out_file, "w", encoding="utf-8")

def log(msg):
    print(msg)
    f.write(str(msg) + "\n")
    f.flush()

windows = []
def enum_cb(hwnd, _):
    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
    title = win32gui.GetWindowText(hwnd)
    cls = win32gui.GetClassName(hwnd)
    vis = win32gui.IsWindowVisible(hwnd)
    if vis or "Sword3" in cls or "vggame" in title.lower() or "vo lam" in title.lower():
        windows.append((hwnd, pid.value, title, cls, vis))
    return True

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

log(f"Total windows inspected: {len(windows)}")
for h, pid, t, c, v in windows:
    if "Sword3" in c or "vggame" in t.lower() or "vo lam" in t.lower() or pid in (45384, 12392, 54828, 62736):
        log(f"HWND: 0x{h:08X} | PID: {pid} | Visible: {v} | Class: '{c}' | Title: '{t}'")

# Take full desktop screenshot
try:
    shot = ImageGrab.grab()
    shot_path = r"c:\Projects\JX\logs\real_desktop_now.png"
    shot.save(shot_path)
    log(f"Desktop screenshot saved to {shot_path} ({shot.width}x{shot.height})")
except Exception as e:
    log(f"Failed to grab desktop: {e}")

f.close()
