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

ARTIFACTS_DIR = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a"
EXE_PATH = r"C:\Projects\JX\runtime\JXHelper_Runtime.exe"
CWD = r"C:\Projects\JX\runtime"

print(f"[TEST] Starting JXHelper from: {EXE_PATH}")
proc = subprocess.Popen([EXE_PATH], cwd=CWD)
print(f"[TEST] Launched PID: {proc.pid}")
time.sleep(2.5)

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)

main_hwnds = []
def enum_main(h, _):
    txt_len = user32.GetWindowTextLengthW(h) + 1
    buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, buf, txt_len)
    title = buf.value
    if "JXHelper" in title and user32.IsWindowVisible(h):
        _, pid = win32process.GetWindowThreadProcessId(h)
        main_hwnds.append((h, pid, title))
    return True

user32.EnumWindows(WNDENUMPROC(enum_main), 0)
print(f"[TEST] Found JXHelper windows: {main_hwnds}")

if not main_hwnds:
    print("[FAIL] Could not find JXHelper main window!")
    proc.terminate()
    sys.exit(1)

main_hwnd, _, main_title = main_hwnds[0]
rect_main = win32gui.GetWindowRect(main_hwnd)
print(f"[TEST] Main HWND: {hex(main_hwnd)}, Title: '{main_title}', Rect: {rect_main}")

# Switch to tab L.công (Tab index 1)
# Find TabControl
children = []
def enum_children(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    txt_len = user32.GetWindowTextLengthW(h) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, txt_buf, txt_len)
    r = win32gui.GetWindowRect(h)
    mr = win32gui.GetWindowRect(main_hwnd)
    rel = (r[0] - mr[0], r[1] - mr[1], r[2] - r[0], r[3] - r[1])
    children.append((h, cls_buf.value, txt_buf.value, rel))
    return True

user32.EnumChildWindows(main_hwnd, WNDENUMPROC(enum_children), 0)

tab_ctrl = None
btn_support = None
for h, cls, txt, rel in children:
    if "SysTabControl32" in cls:
        tab_ctrl = h
    if "Button" in cls and ("Hỗ trợ" in txt or "Nga My" in txt or "Ngũ Độc" in txt or "H.trợ" in txt):
        btn_support = h

WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
MK_LBUTTON = 0x0001
TCM_SETCURSEL = 0x130C
def make_lparam(x, y):
    return (y << 16) | (x & 0xFFFF)

if tab_ctrl:
    print(f"[TEST] Found TabControl: {hex(tab_ctrl)}. Selecting Tab 1 (L.công)...")
    user32.SendMessageW(tab_ctrl, TCM_SETCURSEL, 1, 0)
    # also simulate click on tab header
    user32.PostMessageW(tab_ctrl, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(55, 10))
    user32.PostMessageW(tab_ctrl, WM_LBUTTONUP, 0, make_lparam(55, 10))
    time.sleep(0.5)

# Re-scan children after tab click
children.clear()
user32.EnumChildWindows(main_hwnd, WNDENUMPROC(enum_children), 0)
for h, cls, txt, rel in children:
    if "Button" in cls and ("Hỗ trợ" in txt or "Nga My" in txt or "Ngũ Độc" in txt or "H.trợ" in txt):
        btn_support = h
        print(f"[TEST] Found btnSupportSkills: {hex(h)}, Text: '{txt}', Rel: {rel}")

# Capture Main Window with Tab L.công active
time.sleep(0.5)
rect_main = win32gui.GetWindowRect(main_hwnd)
img_main = ImageGrab.grab(bbox=rect_main)
main_screenshot_path = os.path.join(ARTIFACTS_DIR, "jxhelper_combat_tab_with_support_btn.png")
img_main.save(main_screenshot_path)
print(f"[SUCCESS] Saved main window screenshot to: {main_screenshot_path}")

if not btn_support:
    print("[FAIL] btnSupportSkills button not found!")
    proc.terminate()
    sys.exit(1)

# Click btnSupportSkills to open SupportSkillsForm
print(f"[TEST] Clicking btnSupportSkills ({hex(btn_support)})...")
user32.PostMessageW(btn_support, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(10, 10))
user32.PostMessageW(btn_support, WM_LBUTTONUP, 0, make_lparam(10, 10))
time.sleep(1.5)

# Find SupportSkillsForm dialog ("Chieu thuc ho tro")
dlg_hwnds = []
def enum_dlg(h, _):
    txt_len = user32.GetWindowTextLengthW(h) + 1
    buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, buf, txt_len)
    title = buf.value
    if ("Chieu thuc ho tro" in title or "Hỗ trợ" in title) and user32.IsWindowVisible(h):
        dlg_hwnds.append((h, title))
    return True

user32.EnumWindows(WNDENUMPROC(enum_dlg), 0)
print(f"[TEST] Found Support dialog windows: {dlg_hwnds}")

if not dlg_hwnds:
    print("[FAIL] SupportSkillsForm dialog did not appear!")
    proc.terminate()
    sys.exit(1)

dlg_hwnd, dlg_title = dlg_hwnds[0]
rect_dlg = win32gui.GetWindowRect(dlg_hwnd)
print(f"[TEST] Support Dialog HWND: {hex(dlg_hwnd)}, Title: '{dlg_title}', Rect: {rect_dlg}")

# Capture high-res screenshot of SupportSkillsForm
img_dlg = ImageGrab.grab(bbox=rect_dlg)
dlg_screenshot_path = os.path.join(ARTIFACTS_DIR, "jxhelper_support_dialog_live.png")
img_dlg.save(dlg_screenshot_path)
print(f"[SUCCESS] Saved SupportSkillsForm screenshot to: {dlg_screenshot_path}")

# Enumerate and log all controls on the Support dialog
dlg_children = []
def enum_dlg_children(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    txt_len = user32.GetWindowTextLengthW(h) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, txt_buf, txt_len)
    r = win32gui.GetWindowRect(h)
    mr = win32gui.GetWindowRect(dlg_hwnd)
    rel = (r[0] - mr[0], r[1] - mr[1], r[2] - r[0], r[3] - r[1])
    dlg_children.append((h, cls_buf.value, txt_buf.value, rel))
    return True

user32.EnumChildWindows(dlg_hwnd, WNDENUMPROC(enum_dlg_children), 0)
print(f"\n[TEST] --- Controls in SupportSkillsForm ({len(dlg_children)} items) ---")
for h, cls, txt, rel in dlg_children:
    if txt.strip():
        print(f"  - [{cls}] '{txt.strip()}' at rel {rel}")

# Click 'Lưu & Đóng' button
btn_save = None
for h, cls, txt, rel in dlg_children:
    if "Button" in cls and "Lưu" in txt:
        btn_save = h
        break

if btn_save:
    print(f"\n[TEST] Clicking 'Lưu & Đóng' ({hex(btn_save)})...")
    user32.PostMessageW(btn_save, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(10, 10))
    user32.PostMessageW(btn_save, WM_LBUTTONUP, 0, make_lparam(10, 10))
    time.sleep(1.0)
    print("[TEST] Dialog closed cleanly.")

# Terminate test process
proc.terminate()
print("[TEST] All verification steps completed successfully!")
