import ctypes, time
from PIL import ImageGrab
import win32gui

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

hwnd = 0x2f0bf4 # PID 32572 (nguvansi / BoCuaCacCon)

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

def click(x, y):
    lp = make_lparam(x, y)
    user32.PostMessageW(hwnd, 0x0200, 0, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, 0x0201, 1, lp)
    time.sleep(0.08)
    user32.PostMessageW(hwnd, 0x0202, 0, lp)
    time.sleep(0.05)

def send_key(vk):
    lp = (0x1C << 16) | 1
    user32.PostMessageW(hwnd, 0x0100, vk, lp)
    time.sleep(0.04)
    user32.PostMessageW(hwnd, 0x0101, vk, lp | (3 << 30))
    time.sleep(0.04)

def send_char(c):
    lp = (ord(c) << 16) | 1
    user32.PostMessageW(hwnd, 0x0102, ord(c), lp)
    time.sleep(0.06)

def capture(name):
    if win32gui.IsWindow(hwnd):
        rect = win32gui.GetWindowRect(hwnd)
        if rect[2] > rect[0] and rect[3] > rect[1]:
            img = ImageGrab.grab(bbox=rect, all_screens=True)
            img.save(rf"c:\Projects\JX\logs\{name}")
            print(f"Captured {name}")

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

# Step 1: Click directly in Password field (464, 342)
print("Focusing password field...")
click(464, 342)
time.sleep(0.1)

# Clear any possible characters
for _ in range(25):
    send_key(0x08)
time.sleep(0.1)

# Type Ngu123@@
print("Typing password 'Ngu123@@'...")
for c in "Ngu123@@":
    send_char(c)
time.sleep(0.3)

# Capture password typed (we should see asterisks!)
capture("p32572_pw_typed.png")

# Step 2: Submit login
print("Submitting login...")
click(260, 503) # or VK_RETURN
send_key(0x0D)  # VK_RETURN
time.sleep(4.0)

# Capture post-login screen (Character selection or in-game!)
capture("p32572_after_login_success.png")

with open(r"c:\Projects\JX\logs\p32572_type_status.txt", "w") as f:
    f.write("DONE\n")
