import ctypes, time, sys, os
from PIL import ImageGrab
import win32gui, win32process, psutil

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

# Check existing windows
existing_hwnds = set()
def cb(h, _):
    if win32gui.GetClassName(h) == "Sword3 Class":
        existing_hwnds.add(h)
win32gui.EnumWindows(cb, None)

print(f"Existing Sword3 windows: {[hex(h) for h in existing_hwnds]}")
print("Launching Game.exe with runas...")
res = shell32.ShellExecuteW(None, "runas", r"C:\JXVCTK\JxVoCongTruyenKy\Game.exe", None, r"C:\JXVCTK\JxVoCongTruyenKy", 1)
print(f"ShellExecuteW returned: {res}")

target_hwnd = None
start_t = time.time()
while time.time() - start_t < 25:
    time.sleep(1.0)
    current_hwnds = []
    def cb2(h, _):
        if win32gui.GetClassName(h) == "Sword3 Class":
            current_hwnds.append(h)
    win32gui.EnumWindows(cb2, None)
    diff = set(current_hwnds) - existing_hwnds
    if diff:
        target_hwnd = list(diff)[0]
        print(f"[{time.time()-start_t:.1f}s] Found new game window: {hex(target_hwnd)}")
        break

if not target_hwnd:
    print("Failed to find game window!")
    sys.exit(1)

def capture(name):
    if win32gui.IsWindow(target_hwnd):
        rect = win32gui.GetWindowRect(target_hwnd)
        img = ImageGrab.grab(bbox=rect, all_screens=True)
        path = rf"c:\Projects\JX\logs\title_{name}.png"
        img.save(path)
        print(f"  [Saved] {path}")

# Wait for DirectX
print("Waiting 5.0s for DirectX texture load...")
time.sleep(5.0)
capture("0_loaded")

# Test 1: WM_ACTIVATE & SetForegroundWindow
print("Setting foreground and sending WM_ACTIVATE...")
user32.SetForegroundWindow(target_hwnd)
user32.PostMessageW(target_hwnd, 0x0006, 1, 0) # WA_ACTIVE
user32.PostMessageW(target_hwnd, 0x0007, 0, 0) # WM_SETFOCUS
time.sleep(0.5)

# Test 2: Click with mouse move
print("Sending WM_MOUSEMOVE, WM_LBUTTONDOWN, WM_LBUTTONUP at (400, 385)...")
lp = ((385 & 0xFFFF) << 16) | (400 & 0xFFFF)
user32.PostMessageW(target_hwnd, 0x0200, 0, lp) # WM_MOUSEMOVE
time.sleep(0.05)
user32.PostMessageW(target_hwnd, 0x0201, 1, lp) # WM_LBUTTONDOWN
time.sleep(0.1)
user32.PostMessageW(target_hwnd, 0x0202, 0, lp) # WM_LBUTTONUP
time.sleep(1.5)
capture("1_after_click")

# Test 3: If still at title, try double-click
print("Sending double-click at (400, 385)...")
user32.PostMessageW(target_hwnd, 0x0200, 0, lp)
time.sleep(0.04)
user32.PostMessageW(target_hwnd, 0x0201, 1, lp)
time.sleep(0.05)
user32.PostMessageW(target_hwnd, 0x0202, 0, lp)
time.sleep(0.05)
user32.PostMessageW(target_hwnd, 0x0203, 1, lp) # WM_LBUTTONDBLCLK
time.sleep(0.05)
user32.PostMessageW(target_hwnd, 0x0202, 0, lp)
time.sleep(1.5)
capture("2_after_dblclick")

# Test 4: Key Enter
print("Sending VK_RETURN keydown/keyup...")
sc = user32.MapVirtualKeyW(0x0D, 0)
lp_down = 1 | (sc << 16)
lp_up = 1 | (sc << 16) | (1 << 30) | (1 << 31)
user32.PostMessageW(target_hwnd, 0x0100, 0x0D, lp_down)
time.sleep(0.08)
user32.PostMessageW(target_hwnd, 0x0101, 0x0D, lp_up)
time.sleep(2.0)
capture("3_after_enter")

# Test 5: WM_CHAR Enter (13)
print("Sending WM_CHAR 13...")
user32.PostMessageW(target_hwnd, 0x0102, 13, lp_down)
time.sleep(2.0)
capture("4_after_wm_char")

print("Done with title click tests!")
