import ctypes, struct
from ctypes import wintypes
import win32gui, win32process

user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32

hdesk = user32.OpenInputDesktop(0, False, 0x01FF)
if hdesk:
    user32.SetThreadDesktop(hdesk)

log_path = r"c:\Projects\JX\logs\dump_autos_text.txt"
lines = []

def dump_window(hwnd, name):
    lines.append(f"\n=================== {name} (HWND {hex(hwnd)}) ===================")
    tid, pid = win32process.GetWindowThreadProcessId(hwnd)
    lines.append(f"PID: {pid}")
    
    def cb(ch, _):
        cls = win32gui.GetClassName(ch)
        txt = win32gui.GetWindowText(ch)
        lines.append(f"  Child {hex(ch)} [{cls}]: '{txt}'")
        if "ListView" in cls:
            # dump listview items
            LVM_GETITEMCOUNT = 0x1000 + 4
            LVM_GETITEMTEXTW = 0x1000 + 115
            count = user32.SendMessageW(ch, LVM_GETITEMCOUNT, 0, 0)
            lines.append(f"    -> ListView items count: {count}")
            hProc = kernel32.OpenProcess(0x0038, False, pid)
            if hProc:
                pRemote = kernel32.VirtualAllocEx(hProc, None, 1024, 0x1000, 0x04)
                pText = pRemote + 128
                for row in range(count):
                    row_texts = []
                    for col in range(6):
                        lv_data = struct.pack('<IIiiIIII', 0x0001, row, col, 0, 0, pText, 256, 0)
                        kernel32.WriteProcessMemory(hProc, pRemote, lv_data, len(lv_data), None)
                        user32.SendMessageW(ch, LVM_GETITEMTEXTW, row, pRemote)
                        buf = ctypes.create_unicode_buffer(256)
                        kernel32.ReadProcessMemory(hProc, pText, buf, 512, None)
                        if buf.value:
                            row_texts.append(f"c{col}='{buf.value}'")
                    lines.append(f"      Row {row}: {', '.join(row_texts)}")
                kernel32.VirtualFreeEx(hProc, pRemote, 0, 0x8000)
                kernel32.CloseHandle(hProc)
    win32gui.EnumChildWindows(hwnd, cb, None)

# Find AutoVLBS and Auto Kim Yen
def find_cb(h, _):
    t = win32gui.GetWindowText(h)
    if "KY-" in t or "kimyen" in t.lower() or "Auto" in t:
        dump_window(h, t)
    elif "jxvocong" in t.lower():
        dump_window(h, t)

win32gui.EnumWindows(find_cb, None)

with open(log_path, "w", encoding="utf-8") as f:
    f.write("\n".join(lines))
print(f"Dumped text to {log_path}")
