import os
import sys
import time
import subprocess
import ctypes
from ctypes import wintypes
import win32gui
import win32process
import psutil
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"
LOGS_DIR = r"c:\Projects\JX\logs"
EXE_PATH = r"C:\Projects\JX\runtime\JXHelper_Runtime.exe"
CWD = r"C:\Projects\JX\runtime"

# Kill any existing JXHelper
for p in psutil.process_iter(['pid', 'name']):
    if 'JXHelper' in (p.info['name'] or ''):
        try:
            p.kill()
            print(f"Killed existing PID {p.pid}")
        except Exception:
            pass
time.sleep(1)

# Ensure no trigger file exists
trigger = r"c:\Projects\JX\logs\run_test.trigger"
if os.path.exists(trigger):
    try:
        os.remove(trigger)
    except Exception:
        pass

print(f"[LAUNCH] Starting {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"[LAUNCH] PID: {proc.pid}")

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"[FOUND] Found window after {attempt+1}s: HWND {hex(main_hwnd)}, Title '{main_title}'")
        break
    else:
        print(f"[WAIT] Waiting for window... ({attempt+1}s)")

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

user32.ShowWindow(main_hwnd, 9) # SW_RESTORE
user32.SetForegroundWindow(main_hwnd)
time.sleep(1.0)

# Enumerate child windows to find ListView and Controls
children = []
rect_main = win32gui.GetWindowRect(main_hwnd)

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)

lvw = None
for h, cls, txt, 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:
    print("[ACTION] Clicking BoCuaCacCon (Item 1 @ Y=42)...")
    user32.PostMessageW(lvw, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(50, 42))
    user32.PostMessageW(lvw, WM_LBUTTONUP, 0, make_lparam(50, 42))
    time.sleep(1.5)

# Refresh children and print active controls
children.clear()
rect_main = win32gui.GetWindowRect(main_hwnd)
user32.EnumChildWindows(main_hwnd, WNDENUMPROC(enum_children), 0)

print("\n=== ACTIVE CONTROLS AFTER SELECTING BOCUACACCON ===")
for h, cls, txt, rel in children:
    if txt.strip():
        print(f"  [{cls}] '{txt.strip()}' @ rel {rel}")

# Capture real window
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 = ImageGrab.grab(bbox=rect_main)
    out_art = os.path.join(ARTIFACTS_DIR, "jxhelper_cai_bang_khang_long_live.png")
    out_log = os.path.join(LOGS_DIR, "jxhelper_cai_bang_khang_long_live.png")
    img.save(out_art)
    img.save(out_log)
    print(f"\n[PASS] Saved real desktop screenshot to:\n  {out_art}\n  {out_log}")

# Clean up
try:
    proc.terminate()
except Exception:
    pass

print("[DONE] Verification finished.")
