import os
import sys
import time
import ctypes
from ctypes import wintypes

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

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

# Attach to input desktop
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk:
    user32.SetThreadDesktop(hdesk)
    log(f"SetThreadDesktop attached: {hdesk}")

WM_COMMAND = 0x0111
WM_CLOSE = 0x0010
BM_CLICK = 0x00F5
IDOK = 1

# Enumerate windows for PID 42272
target_pid = 42272
game_hwnd = None
error_hwnds = []

def enum_cb(hwnd, lparam):
    global game_hwnd
    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
    if pid.value == target_pid:
        length = user32.GetWindowTextLengthW(hwnd) + 1
        buf = ctypes.create_unicode_buffer(length)
        user32.GetWindowTextW(hwnd, buf, length)
        cls_buf = ctypes.create_unicode_buffer(256)
        user32.GetClassNameW(hwnd, cls_buf, 256)
        vis = user32.IsWindowVisible(hwnd)
        if cls_buf.value == "#32770":
            error_hwnds.append((hwnd, buf.value))
        elif cls_buf.value == "Sword3 Class":
            game_hwnd = hwnd
    return True

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

log(f"Found game_hwnd: {hex(game_hwnd) if game_hwnd else None}, error_hwnds: {[(hex(h), t) for h, t in error_hwnds]}")

for h, title in error_hwnds:
    log(f"Attempting to dismiss error dialog {hex(h)} '{title}'...")
    # Try WM_COMMAND IDOK
    user32.PostMessageW(h, WM_COMMAND, IDOK, 0)
    user32.PostMessageW(h, WM_CLOSE, 0, 0)

time.sleep(1)

# Check again
error_hwnds.clear()
user32.EnumWindows(WNDENUMPROC(enum_cb), 0)
log(f"After dismissal - error_hwnds: {[(hex(h), t) for h, t in error_hwnds]}")

# Capture game window if present
if game_hwnd:
    import win32gui, win32ui
    from PIL import Image
    rect = win32gui.GetClientRect(game_hwnd)
    w = rect[2] - rect[0]
    h = rect[3] - rect[1]
    if w > 0 and h > 0:
        hwndDC = win32gui.GetWindowDC(game_hwnd)
        mfcDC = win32ui.CreateDCFromHandle(hwndDC)
        saveDC = mfcDC.CreateCompatibleDC()
        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
        saveDC.SelectObject(saveBitMap)
        ctypes.windll.user32.PrintWindow(game_hwnd, saveDC.GetSafeHdc(), 0)
        bmpinfo = saveBitMap.GetInfo()
        bmpstr = saveBitMap.GetBitmapBits(True)
        img = Image.frombuffer('RGB', (bmpinfo['bmWidth'], bmpinfo['bmHeight']), bmpstr, 'raw', 'BGRX', 0, 1)
        savePath = r'c:\Projects\JX\logs\game_after_dismiss.png'
        img.save(savePath)
        log(f"Saved screenshot to {savePath} ({w}x{h})")
        win32gui.DeleteObject(saveBitMap.GetHandle())
        saveDC.DeleteDC()
        mfcDC.DeleteDC()
        win32gui.ReleaseDC(game_hwnd, hwndDC)

log("Dismiss & test script completed.")
