import ctypes
import sys
import time
from ctypes import wintypes
import win32gui
import psutil
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)

def find_launcher_window():
    results = []
    def cb(h, _):
        pid = wintypes.DWORD()
        user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
        try:
            pname = psutil.Process(pid.value).name().lower()
        except Exception:
            pname = ""
        
        if "autoupdate" in pname:
            length = user32.GetWindowTextLengthW(h)
            buf = ctypes.create_unicode_buffer(length + 1)
            user32.GetWindowTextW(h, buf, length + 1)
            cls_buf = ctypes.create_unicode_buffer(256)
            user32.GetClassNameW(h, cls_buf, 256)
            results.append((h, pid.value, cls_buf.value, buf.value, user32.IsWindowVisible(h)))
        return True

    WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
    user32.EnumWindows(WNDENUMPROC(cb), 0)
    return results

print("Looking for AutoUpdateVCTK window...")
for attempt in range(10):
    wins = find_launcher_window()
    if wins:
        break
    time.sleep(1)

print(f"Found {len(wins)} launcher windows:")
main_hwnd = None
for h, pid, cls, txt, vis in wins:
    print(f"HWND: 0x{h:X}, PID: {pid}, Class: {cls}, Title: '{txt}', Visible: {vis}")
    if vis and (cls == "#32770" or "autoupdate" in txt.lower() or "truyền" in txt.lower()):
        main_hwnd = h

if not main_hwnd and wins:
    # Pick first visible or first
    for h, pid, cls, txt, vis in wins:
        if vis:
            main_hwnd = h
            break
    if not main_hwnd:
        main_hwnd = wins[0][0]

if not main_hwnd:
    print("ERROR: Could not find launcher window!")
    sys.exit(1)

print(f"\nUsing Launcher HWND: 0x{main_hwnd:X}")

# Capture launcher screenshot
rect = win32gui.GetWindowRect(main_hwnd)
print(f"Launcher rect: {rect}")
if rect[2] > rect[0] and rect[3] > rect[1]:
    shot = ImageGrab.grab(bbox=rect)
    shot.save(r"C:\Projects\JX\logs\launcher_current.png")
    print("Saved current launcher screenshot to logs/launcher_current.png")

# Find button 1404
btn_1404 = None
children = []
def child_cb(ch, _):
    ctrl_id = user32.GetDlgCtrlID(ch)
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(ch, cls_buf, 256)
    length = user32.GetWindowTextLengthW(ch)
    buf = ctypes.create_unicode_buffer(length + 1)
    user32.GetWindowTextW(ch, buf, length + 1)
    children.append((ch, ctrl_id, cls_buf.value, buf.value))
    return True

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.EnumChildWindows(main_hwnd, WNDENUMPROC(child_cb), 0)

print(f"\nFound {len(children)} child controls:")
for ch, cid, cls, txt in children:
    print(f"Child HWND: 0x{ch:X}, ID: {cid}, Class: {cls}, Text: '{txt}'")
    if cid == 1404 or "bắt đầu" in txt.lower():
        btn_1404 = ch

if btn_1404:
    print(f"\nFound 'Bắt đầu' button: HWND 0x{btn_1404:X} (ID: 1404)")
    print("Sending BM_CLICK and WM_COMMAND...")
    user32.PostMessageW(btn_1404, 0x00F5, 0, 0) # BM_CLICK
    user32.PostMessageW(main_hwnd, 0x0111, 1404, btn_1404) # WM_COMMAND
    print("Sent click messages successfully!")
else:
    print("WARNING: Button 1404 not found directly by ID, clicking center-bottom of launcher...")
    # Button is located at bottom right: approx (rect[0]+815, rect[1]+550)
    # Let's send click to relative coordinates of launcher
    # Launcher is ~975x675. Button 1404 is at ~815, 550
    pass
