import ctypes, time
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 = 0xe207f6 # PID 30076

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

WM_ACTIVATE = 0x0006
WA_ACTIVE = 1
WM_SETFOCUS = 0x0007
WM_MOUSEMOVE = 0x0200
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
WM_LBUTTONDBLCLK = 0x0203
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101
VK_UP = 0x26
VK_DOWN = 0x28
VK_RETURN = 0x0D

with open(r"c:\Projects\JX\logs\click_test_details.txt", "w", encoding="utf-8") as out:
    out.write(f"Testing on HWND {hex(hwnd)}\n")
    
    # Bring to foreground / activate
    fg_res = user32.SetForegroundWindow(hwnd)
    act_res = user32.PostMessageW(hwnd, WM_ACTIVATE, WA_ACTIVE, 0)
    foc_res = user32.PostMessageW(hwnd, WM_SETFOCUS, 0, 0)
    out.write(f"SetForegroundWindow: {fg_res}, WM_ACTIVATE: {act_res}, WM_SETFOCUS: {foc_res}\n")
    time.sleep(0.3)
    
    # Try sending VK_UP twice: from "Đấu Trường" (row 3) -> "Võ Công Truyền Kỳ" (row 2)
    # But wait, first try clicking (220, 200)
    lp = make_lparam(220, 200)
    user32.PostMessageW(hwnd, WM_MOUSEMOVE, 0, lp)
    time.sleep(0.05)
    r1 = user32.PostMessageW(hwnd, WM_LBUTTONDOWN, 1, lp)
    time.sleep(0.08)
    r2 = user32.PostMessageW(hwnd, WM_LBUTTONUP, 0, lp)
    out.write(f"Click (220, 200): down={r1}, up={r2}\n")
    time.sleep(0.5)

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