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

hwnds = []
def cb(h, _):
    txt_len = user32.GetWindowTextLengthW(h) + 1
    txt_buf = ctypes.create_unicode_buffer(txt_len)
    user32.GetWindowTextW(h, txt_buf, txt_len)
    if "JXHelper" in txt_buf.value and user32.IsWindowVisible(h):
        hwnds.append(h)
    return True
user32.EnumWindows(ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(cb), 0)

main_hwnd = hwnds[0]
children = []
def child_cb(h, _):
    cls_buf = ctypes.create_unicode_buffer(256)
    user32.GetClassNameW(h, cls_buf, 256)
    children.append((h, cls_buf.value))
    return True
user32.EnumChildWindows(main_hwnd, ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)(child_cb), 0)

tab_ctrl = next(h for h, cls in children if "TabControl" in cls or "SysTabControl32" in cls)
print(f"Current TabControl: {hex(tab_ctrl)}")

class RECT(ctypes.Structure):
    _fields_ = [
        ("left", ctypes.c_long),
        ("top", ctypes.c_long),
        ("right", ctypes.c_long),
        ("bottom", ctypes.c_long)
    ]

TCM_GETITEMCOUNT = 0x1304
TCM_GETITEMRECT = 0x130A

cnt = user32.SendMessageW(tab_ctrl, TCM_GETITEMCOUNT, 0, 0)
print(f"Tab count: {cnt}")
tab_centers = []
for i in range(cnt):
    r = RECT()
    user32.SendMessageW(tab_ctrl, TCM_GETITEMRECT, i, ctypes.byref(r))
    cx = (r.left + r.right) // 2
    cy = (r.top + r.bottom) // 2
    tab_centers.append((cx, cy))
    print(f"Tab {i} rect: ({r.left}, {r.top}, {r.right}, {r.bottom}) -> center: ({cx}, {cy})")

# Tab 0 is L.công!
cx0, cy0 = tab_centers[0]
WM_LBUTTONDOWN = 0x0201
WM_LBUTTONUP = 0x0202
MK_LBUTTON = 0x0001
def make_lparam(x, y):
    return (y << 16) | (x & 0xFFFF)

print(f"Clicking Tab 0 (L.công) at center ({cx0}, {cy0})...")
user32.PostMessageW(tab_ctrl, WM_LBUTTONDOWN, MK_LBUTTON, make_lparam(cx0, cy0))
user32.PostMessageW(tab_ctrl, WM_LBUTTONUP, 0, make_lparam(cx0, cy0))
time.sleep(0.5)

rect = win32gui.GetWindowRect(main_hwnd)
img = ImageGrab.grab(bbox=rect)
out = r"C:\Users\Admin\.gemini\antigravity\brain\5f637e30-06d3-43e8-a064-a259fea7be1a\test_tab0_exact.png"
img.save(out)
print(f"Saved {out}")
