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

sys.stdout.reconfigure(encoding='utf-8')
user32 = ctypes.windll.user32
hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk: user32.SetThreadDesktop(hdesk)

hwnd = 0x0063003A

def send_key(vk):
    sc = user32.MapVirtualKeyW(vk, 0)
    lp_down = 1 | (sc << 16)
    lp_up = 1 | (sc << 16) | (3 << 30)
    user32.PostMessageW(hwnd, 0x0100, vk, lp_down)
    time.sleep(0.05)
    user32.PostMessageW(hwnd, 0x0101, vk, lp_up)
    time.sleep(0.05)

def send_shift_key(vk):
    sc_shift = user32.MapVirtualKeyW(0x10, 0) # VK_SHIFT
    sc_vk = user32.MapVirtualKeyW(vk, 0)
    user32.PostMessageW(hwnd, 0x0100, 0x10, 1 | (sc_shift << 16))
    time.sleep(0.02)
    user32.PostMessageW(hwnd, 0x0100, vk, 1 | (sc_vk << 16))
    time.sleep(0.05)
    user32.PostMessageW(hwnd, 0x0101, vk, 1 | (sc_vk << 16) | (3 << 30))
    time.sleep(0.02)
    user32.PostMessageW(hwnd, 0x0101, 0x10, 1 | (sc_shift << 16) | (3 << 30))
    time.sleep(0.05)

def capture(name):
    rect = win32gui.GetWindowRect(hwnd)
    img = ImageGrab.grab(bbox=rect, all_screens=True)
    # Crop dialog area
    crop = img.crop((240, 240, 570, 480))
    path = rf"c:\Projects\JX\logs\{name}.png"
    crop.save(path)
    print(f"Captured: {path}")

user32.SetForegroundWindow(hwnd)
time.sleep(0.2)

capture("key_test_0_initial")

# Test 1: VK_UP
print("Testing VK_UP...")
send_key(0x26)
time.sleep(0.3)
capture("key_test_1_up")

# Test 2: Shift+Tab
print("Testing Shift+Tab...")
send_shift_key(0x09)
time.sleep(0.3)
capture("key_test_2_shifttab")

# Test 3: VK_PRIOR (PageUp)
print("Testing PageUp...")
send_key(0x21)
time.sleep(0.3)
capture("key_test_3_pageup")

# Test 4: Tab repeatedly (up to 6 times to see cycle)
for i in range(1, 7):
    print(f"Testing Tab #{i}...")
    send_key(0x09)
    time.sleep(0.2)
    capture(f"key_test_4_tab_{i}")
