import sys, os, traceback
import ctypes, time
import win32gui, win32con, win32process
from PIL import ImageGrab

log_file = r"c:\Projects\JX\logs\dismiss_err.log"
try:
    user32 = ctypes.windll.user32
    hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
    if hdesk:
        user32.SetThreadDesktop(hdesk)

    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":
                _, pid = win32process.GetWindowThreadProcessId(hwnd)
                popups.append((hwnd, pid))
    win32gui.EnumWindows(enum_cb, None)

    with open(log_file, "w", encoding="utf-8") as f:
        f.write(f"Found {len(popups)} popups\n")
        for hwnd, pid in popups:
            f.write(f"Dismissing {hex(hwnd)} pid {pid}\n")
            btn = win32gui.FindWindowEx(hwnd, 0, "Button", "OK")
            if btn:
                win32gui.SendMessage(btn, win32con.BM_CLICK, 0, 0)
            else:
                win32gui.SendMessage(hwnd, win32con.WM_CLOSE, 0, 0)

    time.sleep(1)
    im = ImageGrab.grab()
    im.save(r"c:\Projects\JX\logs\real_desktop_after_dismiss.png")
    with open(log_file, "a", encoding="utf-8") as f:
        f.write("Successfully grabbed after dismiss screen!\n")
except Exception as e:
    with open(log_file, "a", encoding="utf-8") as f:
        f.write(f"Exception: {e}\n{traceback.format_exc()}")
