import ctypes, time, sys
from ctypes import wintypes
import win32gui
from PIL import ImageGrab

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

hwnd = 0xD0CEC
if not win32gui.IsWindow(hwnd):
    print("HWND not found!")
    sys.exit(1)

# Bring window to foreground temporarily to interact & screenshot
win32gui.SetForegroundWindow(hwnd)
time.sleep(0.5)

rect = win32gui.GetWindowRect(hwnd)
print(f"Window rect: {rect}")

# Send click to "Bắt đầu trò chơi" at (400, 395)
# In client coordinates:
lp = (395 << 16) | 400
user32.PostMessageW(hwnd, 0x0200, 0, lp) # WM_MOUSEMOVE
time.sleep(0.05)
user32.PostMessageW(hwnd, 0x0201, 1, lp) # WM_LBUTTONDOWN
time.sleep(0.1)
user32.PostMessageW(hwnd, 0x0202, 0, lp) # WM_LBUTTONUP
print("Sent click to (400, 395)")

# Also try pressing Enter just in case button is default focused
time.sleep(0.2)
user32.PostMessageW(hwnd, 0x0100, 0x0D, 0)
time.sleep(0.05)
user32.PostMessageW(hwnd, 0x0101, 0x0D, 0)

time.sleep(2.0)

# Capture screenshot
rect = win32gui.GetWindowRect(hwnd)
if rect[2] > rect[0] and rect[3] > rect[1]:
    img = ImageGrab.grab(bbox=rect)
    img.save(r"C:\Projects\JX\logs\game_after_start_click.png")
    print("Saved C:\\Projects\\JX\\logs\\game_after_start_click.png")
