import ctypes, sys, time, shutil
from ctypes import wintypes
import win32gui, win32con, 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)

# Discover all Sword3 Class windows and match with character info
sword3_windows = []
def cb(h, _):
    if user32.IsWindowVisible(h):
        cls_buf = ctypes.create_unicode_buffer(256)
        user32.GetClassNameW(h, cls_buf, 256)
        if cls_buf.value == "Sword3 Class":
            pid = wintypes.DWORD()
            user32.GetWindowThreadProcessId(h, ctypes.byref(pid))
            rect = win32gui.GetWindowRect(h)
            sword3_windows.append((h, pid.value, rect))
    return True

WNDENUMPROC = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.EnumWindows(WNDENUMPROC(cb), 0)

print(f"Discovered {len(sword3_windows)} Sword3 Class windows:")
for h, pid, r in sword3_windows:
    print(f"HWND: 0x{h:08X}, PID: {pid}, Rect: {r}")

# Character map:
# PID 32572: BoCuaCacCon (Cái Bang)
# PID 30076: MeCuaCacCon (Nga My)
# PID 31164: ConCuaBoMe (Thiếu Lâm)
# PID 12768: ConGailCung (Ngũ Độc)
char_map = {
    32572: ("BoCuaCacCon", "CaiBang", "nguvansi"),
    30076: ("MeCuaCacCon", "NgaMy", "nguvansi3"),
    31164: ("ConCuaBoMe", "ThieuLam", "nguvansi1"),
    12768: ("ConGailCung", "NguDoc", "nguvansi2"),
}

results = []
for h, pid, orig_rect in sword3_windows:
    cinfo = char_map.get(pid, (f"Game_{pid}", "Unknown", f"acc_{pid}"))
    cname, sect, user = cinfo
    
    # Save original rect
    ow, oh = orig_rect[2] - orig_rect[0], orig_rect[3] - orig_rect[1]
    
    # Bring to foreground at (50, 50)
    user32.ShowWindow(h, win32con.SW_RESTORE)
    user32.SetWindowPos(h, win32con.HWND_TOPMOST, 50, 50, 806, 629, win32con.SWP_SHOWWINDOW)
    user32.SetForegroundWindow(h)
    time.sleep(0.8)
    
    # Capture cleanly
    img = ImageGrab.grab(bbox=(50, 50, 856, 679))
    log_path = rf"C:\Projects\JX\logs\empirical_{cname}_{sect}.png"
    img.save(log_path)
    
    art_path = rf"C:\Users\Admin\.gemini\antigravity\brain\1b4a0d01-a767-4d3f-966f-116a863fc8de\empirical_{cname}_{sect}.png"
    shutil.copyfile(log_path, art_path)
    
    print(f"SAVED: {cname} ({sect}) PID {pid} -> {art_path}")
    results.append((cname, sect, pid, h, art_path))
    
    # Restore original position
    user32.SetWindowPos(h, win32con.HWND_NOTOPMOST, orig_rect[0], orig_rect[1], ow, oh, win32con.SWP_SHOWWINDOW)
    time.sleep(0.2)

# Also capture full composite view of all windows
time.sleep(0.5)
comp_img = ImageGrab.grab(all_screens=True)
comp_path = r"C:\Projects\JX\logs\all_4_accounts_in_game_composite.png"
comp_img.save(comp_path)
art_comp = r"C:\Users\Admin\.gemini\antigravity\brain\1b4a0d01-a767-4d3f-966f-116a863fc8de\all_4_accounts_in_game_composite.png"
shutil.copyfile(comp_path, art_comp)
print(f"SAVED COMPOSITE: {art_comp}")

with open(r"C:\Projects\JX\logs\all_4_accounts_status.txt", "w", encoding="utf-8") as f:
    f.write("=== 4 ACCOUNTS IN-GAME EMPIRICAL STATUS ===\n")
    for cname, sect, pid, h, path in results:
        f.write(f"Character: {cname} | Sect: {sect} | PID: {pid} | HWND: 0x{h:08X} | Image: {path}\n")
print("Done all 4 captures!")
