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

# 1. Check if JXHelper_Runtime is running; if not, launch it
target_pids = [p.pid for p in psutil.process_iter(['pid', 'name']) if 'JXHelper' in (p.info['name'] or '')]
if not target_pids:
    print("Launching runtime/JXHelper_Runtime.exe...")
    subprocess.Popen([r"C:\Projects\JX\runtime\JXHelper_Runtime.exe"], cwd=r"C:\Projects\JX\runtime")
    time.sleep(2.5)

# 2. Find JXHelper window
hwnds = []
def enum_cb(hwnd, _):
    txt_len = user32.GetWindowTextLengthW(hwnd) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(hwnd, txt_buf, txt_len)
    if "JXHelper" in txt_buf.value and user32.IsWindowVisible(hwnd):
        hwnds.append(hwnd)
    return True

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
for _ in range(10):
    hwnds.clear()
    user32.EnumWindows(WNDENUMPROC(enum_cb), 0)
    if hwnds:
        break
    time.sleep(0.5)

if not hwnds:
    print("LỖI: Không tìm thấy cửa sổ JXHelper!")
    sys.exit(1)

main_hwnd = hwnds[0]
print(f"Main HWND: {hex(main_hwnd)}")
user32.ShowWindow(main_hwnd, 9) # SW_RESTORE
user32.SetForegroundWindow(main_hwnd)
time.sleep(0.5)

# 3. Find ListView
children = []
def child_cb(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    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, rel))
    return True

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

lvw = None
for h, cls, rel in children:
    if "SysListView32" in cls:
        lvw = h
        print(f"Found ListView: {hex(h)}, rel: {rel}")
        break

WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
MK_LBUTTON = 0x0001

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

if lvw:
    # Click Item 1 (BoCuaCacCon - Cái Bang) at Y=42
    print("Clicking Item 1 (BoCuaCacCon - Cái Bang)...")
    user32.PostMessageW(lvw, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(50, 42))
    user32.PostMessageW(lvw, WM_LBUTTONUP, 0, make_lparam(50, 42))
    time.sleep(1.2)

# 4. Capture screenshot of the live real window
rect = win32gui.GetWindowRect(main_hwnd)
print(f"Window rect: {rect}")
img = ImageGrab.grab(bbox=rect)

out_art = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\jxhelper_cai_bang_khang_long_live.png"
out_log = r"c:\Projects\JX\logs\jxhelper_cai_bang_khang_long_live.png"
img.save(out_art)
img.save(out_log)
print(f"XUẤT THÀNH CÔNG ẢNH THỰC TẾ: {out_art}")
