import ctypes, time
import win32gui, win32con, win32process
from PIL import ImageGrab

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

log_path = r"c:\Projects\JX\logs\close_popups_res.txt"
lines = []

popups = []
def enum_cb(hwnd, _):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowVisible(hwnd):
        title = win32gui.GetWindowText(hwnd)
        cls = win32gui.GetClassName(hwnd)
        if title == "Error" and cls == "#32770":
            tid, pid = win32process.GetWindowThreadProcessId(hwnd)
            popups.append((hwnd, pid, tid))

win32gui.EnumWindows(enum_cb, None)
lines.append(f"Found {len(popups)} Error popups:")

for hwnd, pid, tid in popups:
    lines.append(f"Attempting to close HWND {hex(hwnd)} PID {pid}")
    btn = win32gui.FindWindowEx(hwnd, 0, "Button", "OK")
    
    # 1. PostMessage BM_CLICK to button
    if btn:
        win32gui.PostMessage(btn, win32con.BM_CLICK, 0, 0)
    # 2. PostMessage WM_COMMAND 1 to dialog
    win32gui.PostMessage(hwnd, win32con.WM_COMMAND, 1, btn if btn else 0)
    # 3. Post VK_RETURN
    win32gui.PostMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    win32gui.PostMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)
    # 4. EndDialog
    user32.EndDialog(hwnd, 1)

time.sleep(1.5)

# Check remaining
remaining = []
win32gui.EnumWindows(enum_cb, None)
lines.append(f"Remaining popups after close: {len(popups) - len(remaining)} closed, now {len(remaining)} left")

# Re-grab screen
im = ImageGrab.grab()
im.save(r"c:\Projects\JX\logs\real_desktop_now_0844.png")
lines.append("Saved real_desktop_now_0844.png")

with open(log_path, "w", encoding="utf-8") as f:
    f.write("\n".join(lines))
