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', errors='replace')
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}")
DETACHED_PROCESS = 0x00000008
CREATE_NEW_PROCESS_GROUP = 0x00000200
proc = subprocess.Popen(
    [EXE_PATH],
    cwd=CWD,
    creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,
    close_fds=True
)
print(f"[TEST] Launched PID: {proc.pid}")

# Wait and poll for JXHelper window
WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)

main_hwnd = None
main_title = None

for attempt in range(15):
    time.sleep(1.0)
    found = []
    def enum_cb(h, _):
        if user32.IsWindowVisible(h):
            t = win32gui.GetWindowText(h)
            if "JXHelper" in t:
                found.append((h, t))
        return True
    user32.EnumWindows(WNDENUMPROC(enum_cb), 0)
    if found:
        main_hwnd, main_title = found[0]
        print(f"[TEST] Found JXHelper after {attempt+1}s: HWND {hex(main_hwnd)}, Title '{main_title}'")
        break
    else:
        print(f"[TEST] Waiting for window... ({attempt+1}s)")

if not main_hwnd:
    print("[FAIL] Could not find JXHelper window after 15s!")
    sys.exit(1)

rect_main = win32gui.GetWindowRect(main_hwnd)
print(f"[TEST] Main Rect: {rect_main}")

# Bring window to front
user32.SetForegroundWindow(main_hwnd)
time.sleep(0.5)

# Find TabControl and child buttons
children = []
def enum_children(h, _):
    cls = win32gui.GetClassName(h)
    txt = win32gui.GetWindowText(h)
    r = win32gui.GetWindowRect(h)
    rel = (r[0] - rect_main[0], r[1] - rect_main[1], r[2] - r[0], r[3] - r[1])
    children.append((h, cls, txt, 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 or "TabControl" in cls:
        tab_ctrl = h
    if "Button" in cls and ("Hỗ trợ" in txt or "Nga My" in txt or "Ngũ Độc" in txt):
        btn_support = h

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

if tab_ctrl:
    print(f"[TEST] Clicking Tab 1 (L.công) on TabControl {hex(tab_ctrl)}...")
    # Click at tab 1 header coordinate (rel x=55, y=10)
    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.8)

# Re-scan children
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):
        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)
if rect_main[2] > rect_main[0] and rect_main[3] > rect_main[1]:
    img_main = ImageGrab.grab(bbox=rect_main)
    main_shot = os.path.join(ARTIFACTS_DIR, "jxhelper_combat_tab_with_support_btn.png")
    img_main.save(main_shot)
    print(f"[SUCCESS] Saved main window screenshot: {main_shot}")

if not btn_support:
    print("[FAIL] btnSupportSkills not found among children!")
    sys.exit(1)

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

# Find SupportSkillsForm dialog
dlg_found = []
def enum_dlg(h, _):
    if user32.IsWindowVisible(h):
        t = win32gui.GetWindowText(h)
        if "Chieu thuc ho tro" in t or "Hỗ trợ" in t:
            dlg_found.append((h, t))
    return True

user32.EnumWindows(WNDENUMPROC(enum_dlg), 0)
print(f"[TEST] Found support dialogs: {dlg_found}")

if not dlg_found:
    print("[FAIL] SupportSkillsForm window did not appear!")
    sys.exit(1)

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

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

# Enumerate controls on dialog
dlg_children = []
def enum_dlg_ch(h, _):
    cls = win32gui.GetClassName(h)
    txt = win32gui.GetWindowText(h)
    r = win32gui.GetWindowRect(h)
    rel = (r[0] - rect_dlg[0], r[1] - rect_dlg[1], r[2] - r[0], r[3] - r[1])
    dlg_children.append((h, cls, txt, rel))
    return True

user32.EnumChildWindows(dlg_hwnd, WNDENUMPROC(enum_dlg_ch), 0)
print(f"\n[TEST] === CONTROLS IN SupportSkillsForm ({len(dlg_children)} total) ===")
for h, cls, txt, rel in dlg_children:
    if txt.strip():
        print(f"  [{cls}] '{txt.strip()}' @ rel {rel}")

# Click 'Lưu & Đóng' button
btn_save = next((h for h, cls, txt, rel in dlg_children if "Button" in cls and "Lưu" in txt), None)
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.")

print("\n[ALL PASS] UI verification completed successfully!")
