import ctypes, time
from ctypes import wintypes
import win32gui, win32ui
from PIL import Image

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

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

hwnd = 0x002F0BF4 # PID 32572
print(f"Target HWND: {hex(hwnd)}, IsWindow={user32.IsWindow(hwnd)}")

def make_lparam(x, y):
    return (y << 16) | (x & 0xFFFF)

WM_ACTIVATE = 0x0006
WM_SETFOCUS = 0x0007
WM_MOUSEMOVE = 0x0200
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101
VK_RETURN = 0x0D

lparam = make_lparam(400, 395)

# Restore if iconic
if user32.IsIconic(hwnd):
    user32.ShowWindow(hwnd, 9)
    time.sleep(0.5)

user32.PostMessageW(hwnd, WM_ACTIVATE, 1, 0)
user32.PostMessageW(hwnd, WM_SETFOCUS, 0, 0)
time.sleep(0.1)

# Click 'Bắt đầu trò chơi'
user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lparam)
time.sleep(0.05)
user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lparam)
time.sleep(0.1)
user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lparam)
time.sleep(0.15)

# Also send ENTER
lparam_key = (0x1C << 16) | 1
user32.PostMessageW(hwnd, WM_KEYDOWN, VK_RETURN, lparam_key)
time.sleep(0.06)
user32.PostMessageW(hwnd, WM_KEYUP, VK_RETURN, lparam_key | (3 << 30))

print("Clicked and sent Enter! Waiting 3s for transition...")
time.sleep(3)

# Capture result
rect = win32gui.GetClientRect(hwnd)
w = rect[2] - rect[0]
h_h = rect[3] - rect[1]
if w > 0 and h_h > 0:
    hwndDC = win32gui.GetWindowDC(hwnd)
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h_h)
    saveDC.SelectObject(saveBitMap)
    user32.PrintWindow(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\after_single_click_start.png'
    img.save(savePath)
    print(f"Captured {savePath}")
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()
    mfcDC.DeleteDC()
    win32gui.ReleaseDC(hwnd, hwndDC)

with open(r'c:\Projects\JX\logs\single_click_result.txt', 'w', encoding='utf-8') as f:
    f.write("Completed single click start test.\n")
