import ctypes, time
import win32gui
from PIL import ImageGrab

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

hwnd = 0xe207f6 # PID 30076

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

WM_MOUSEMOVE = 0x0200
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
WM_LBUTTONDBLCLK = 0x0203

def click_client(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp)
    time.sleep(0.08)
    user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
    time.sleep(0.05)

def dblclick_client(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp)
    time.sleep(0.03)
    user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
    time.sleep(0.08)
    user32.PostMessageW(hwnd, WM_LBUTTONDBLCLK, 1, lp)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
    time.sleep(0.05)

# Step 1: Click "Võ Công Truyền Kỳ" on the left
print("Clicking 'Võ Công Truyền Kỳ' on left (240, 186)...")
click_client(240, 186)
time.sleep(0.5)

# Step 2: Click "Trọn Vẹn Chữ Tình" on the right
print("Clicking 'Trọn Vẹn Chữ Tình' on right (550, 195)...")
click_client(550, 195)
time.sleep(0.3)
dblclick_client(550, 195)
time.sleep(0.5)

# Step 3: Click "Xác định" bottom-left
print("Clicking 'Xác định' (260, 503)...")
click_client(260, 503)
time.sleep(2.5)

rect = win32gui.GetWindowRect(hwnd)
img = ImageGrab.grab(bbox=rect, all_screens=True)
img.save(r"c:\Projects\JX\logs\pid_30076_after_select_vctk.png")
print("Saved pid_30076_after_select_vctk.png")
