"""Probe MCSJ through Java Access Bridge using 32-bit Python.
Run with: C:\MCSJAgent\Python311-32-embed\python.exe C:\MCSJAgent\mcsj-jab-probe.py
If it says no java window, restart MCSJ after jabswitch /enable.
"""
from pyjab.jabdriver import JABDriver
import json, sys, traceback
TITLE = 'MCSJ - 2026.1 (chestervillagenydb)'
DLL = r'C:\Edmunds\MCSJ26.1\jre\bin\WindowsAccessBridge-32.dll'

def node(el, depth=0, max_depth=6, max_nodes=[0]):
    if max_nodes[0] >= 500:
        return None
    max_nodes[0] += 1
    try:
        d = {
            'n': max_nodes[0],
            'depth': depth,
            'name': el.name,
            'role': el.role,
            'description': el.description,
            'states': el.states,
            'x': el.x, 'y': el.y, 'w': el.width, 'h': el.height,
            'children_count': el.children_count,
        }
        if depth < max_depth:
            kids=[]
            for child in el.children:
                c=node(child, depth+1, max_depth, max_nodes)
                if c: kids.append(c)
            if kids: d['children']=kids
        return d
    except Exception as e:
        return {'depth': depth, 'error': repr(e)}

try:
    d=JABDriver(title=TITLE, bridge_dll=DLL, timeout=12)
    root=d.root_element
    out={'ok': True, 'hwnd': int(d.hwnd), 'pid': d.pid, 'vmid': d.vmid, 'version': d.get_version_info(), 'tree': node(root)}
    print(json.dumps(out, indent=2))
except Exception as e:
    print(json.dumps({'ok': False, 'error_type': type(e).__name__, 'error': str(e), 'hint': 'MCSJ is likely 32-bit Java and may need restart after Java Access Bridge enable; run jabswitch /enable then restart MCSJ.'}, indent=2))
    sys.exit(1)
