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

sys.stdout.reconfigure(encoding='utf-8')
log_file = r"C:\Projects\JX\logs\launcher_start_test.log"

def log(msg):
    ts = time.strftime("[%Y-%m-%d %H:%M:%S]")
    line = f"{ts} {msg}\n"
    print(line, end='')
    with open(log_file, "a", encoding="utf-8") as f:
        f.write(line)

with open(log_file, "w", encoding="utf-8") as f:
    f.write("=== LAUNCHER START TEST ===\n")

user32 = ctypes.windll.user32
shell32 = ctypes.windll.shell32
kernel32 = ctypes.windll.kernel32

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

# Record existing Sword3 windows
existing_sword3 = []
def cb_s(h, _):
    if win32gui.GetClassName(h) == "Sword3 Class":
        existing_sword3.append(h)
win32gui.EnumWindows(cb_s, None)
log(f"Existing Sword3 windows: {[hex(h) for h in existing_sword3]}")

# 1. Start AutoUpdateVCTK if not running
launcher_pids = [p.pid for p in psutil.process_iter(['name', 'pid']) if 'autoupdate' in (p.info['name'] or '').lower()]
if not launcher_pids:
    log("Starting AutoUpdateVCTK.exe...")
    os.startfile(r"C:\JXVCTK\JxVoCongTruyenKy\AutoUpdateVCTK.exe")
    time.sleep(3.0)
else:
    log(f"AutoUpdateVCTK already running: PID {launcher_pids}")

# 2. Find launcher and modal windows
launcher_hwnd = None
for attempt in range(15):
    def find_cb(h, _):
        global launcher_hwnd
        if user32.IsWindowVisible(h):
            _, pid = win32process.GetWindowThreadProcessId(h)
            try:
                pname = psutil.Process(pid).name().lower()
                if "autoupdate" in pname:
                    txt = win32gui.GetWindowText(h)
                    cls = win32gui.GetClassName(h)
                    if txt == "Mở Auto" or cls == "#32770":
                        log(f"Dismissing modal popup: HWND {hex(h)} '{txt}'")
                        user32.PostMessageW(h, 0x0010, 0, 0) # WM_CLOSE
                    else:
                        launcher_hwnd = h
            except Exception:
                pass
        return True
    win32gui.EnumWindows(find_cb, None)
    if launcher_hwnd:
        break
    time.sleep(1.0)

if not launcher_hwnd:
    log("FATAL: Launcher window not found!")
    sys.exit(1)

log(f"Found Launcher HWND: {hex(launcher_hwnd)}")
time.sleep(1.0)

# Dismiss modal again if still present
def dismiss_again(h, _):
    if user32.IsWindowVisible(h):
        txt = win32gui.GetWindowText(h)
        if txt == "Mở Auto":
            log(f"Closing 'Mở Auto' dialog: {hex(h)}")
            user32.PostMessageW(h, 0x0010, 0, 0)
    return True
win32gui.EnumWindows(dismiss_again, None)
time.sleep(0.5)

# 3. Find button 1404 "Bắt đầu"
btn_1404 = None
def child_cb(ch, _):
    global btn_1404
    cid = user32.GetDlgCtrlID(ch)
    txt = win32gui.GetWindowText(ch)
    if cid == 1404 or "bắt đầu" in txt.lower():
        btn_1404 = ch
    return True

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

if btn_1404:
    log(f"Found 'Bắt đầu' button: HWND {hex(btn_1404)} (ID: 1404)")
    user32.PostMessageW(btn_1404, 0x00F5, 0, 0) # BM_CLICK
    user32.PostMessageW(launcher_hwnd, 0x0111, 1404, btn_1404) # WM_COMMAND
else:
    log("Button 1404 not found, clicking coordinates (815, 550)...")
    lp = ((550 & 0xFFFF) << 16) | (815 & 0xFFFF)
    user32.PostMessageW(launcher_hwnd, 0x0200, 0, lp)
    time.sleep(0.05)
    user32.PostMessageW(launcher_hwnd, 0x0201, 1, lp)
    time.sleep(0.08)
    user32.PostMessageW(launcher_hwnd, 0x0202, 0, lp)

log("Sent click to 'Bắt đầu'! Waiting up to 30s for new Sword3 Class window...")

# 4. Wait for new Sword3 window
new_game_hwnd = None
start_t = time.time()
while time.time() - start_t < 30:
    time.sleep(1.0)
    current_sword3 = []
    def cb_cur(h, _):
        if win32gui.GetClassName(h) == "Sword3 Class":
            current_sword3.append(h)
    win32gui.EnumWindows(cb_cur, None)
    diff = set(current_sword3) - set(existing_sword3)
    if diff:
        new_game_hwnd = list(diff)[0]
        log(f"SUCCESS! Detected new game window: HWND {hex(new_game_hwnd)} after {time.time()-start_t:.1f}s")
        break

if not new_game_hwnd:
    log("FAILED: New game window did not appear!")
    sys.exit(1)

time.sleep(4.0)
rect = win32gui.GetWindowRect(new_game_hwnd)
img = ImageGrab.grab(bbox=rect, all_screens=True)
img.save(r"C:\Projects\JX\logs\new_game_from_launcher.png")
log("Saved screenshot: logs/new_game_from_launcher.png")
log("=== LAUNCHER TEST SUCCESSFUL ===")
