import ctypes, time
from ctypes import wintypes

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

def log(msg):
    with open(r'c:\Projects\JX\logs\dismiss_detail.log', 'a', encoding='utf-8') as f:
        f.write(f"[{time.strftime('%H:%M:%S')}] {msg}\n")

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

target_pid = 42272
errs = []

def cb(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    if cls_buf.value == '#32770':
        pid = wintypes.DWORD()
        user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
        if pid.value == target_pid:
            errs.append(h)
    return True

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

log(f"Found dialogs: {[hex(x) for x in errs]}")

for dlg in errs:
    # Find all child buttons
    def child_cb(ch, _):
        cls_buf = ctypes.create_unicode_buffer(256)
        user32.GetClassNameW(ch, cls_buf, 256)
        if cls_buf.value == 'Button':
            ctrl_id = user32.GetDlgCtrlID(ch)
            log(f"Found button {hex(ch)}, CtrlID: {ctrl_id}")
            
            # Post BM_CLICK
            r1 = user32.PostMessageW(ch, 0x00F5, 0, 0)
            log(f"PostMessage BM_CLICK to {hex(ch)}: {r1}")
            
            # Post WM_COMMAND to dlg
            r2 = user32.PostMessageW(dlg, 0x0111, ctrl_id, ch)
            log(f"PostMessage WM_COMMAND {ctrl_id} to dlg: {r2}")
        return True
    
    WNDENUMPROC_CHILD = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
    user32.EnumChildWindows(dlg, WNDENUMPROC_CHILD(child_cb), 0)

time.sleep(1)
errs.clear()
user32.EnumWindows(WNDENUMPROC(cb), 0)
log(f"After 1s dialogs: {[hex(x) for x in errs]}")
