"""Direct JAB click using 32-bit Python + pyjab. Navigates from root to dialog buttons."""
import sys, time

DLL = r"C:\Edmunds\MCSJ26.1\jre\bin\WindowsAccessBridge-32.dll"
TITLE = "MCSJ - 2026.1"

sys.path.insert(0, r"C:\MCSJAgent\Python311-32-embed\Lib\site-packages")

from pyjab.jabdriver import JABDriver

def find_buttons(el, depth=0, max_depth=15, target_name=None):
    """DFS from el, collect push buttons."""
    if depth > max_depth:
        return []
    try:
        info = el.get_element_information()
    except Exception:
        return []
    role = (info.get("role") or "").lower()
    name = info.get("name") or ""
    results = []
    if role == "push button":
        results.append((name, el, info))
        print(f"  BUTTON depth={depth} name={name!r} bounds={info.get('bounds')}")
    try:
        kids = list(el._generate_childs_from_element(el, visible=False))
    except Exception:
        kids = []
    for kid in kids:
        results.extend(find_buttons(kid, depth+1, max_depth, target_name))
    return results

def main():
    target = sys.argv[1] if len(sys.argv) > 1 else "Add"
    print(f"Connecting to MCSJ via JAB, looking for button: {target!r}")

    driver = JABDriver(title=TITLE, bridge_dll=DLL, timeout=10)
    root = driver.root_element

    print("Root connected. Traversing to dialog...")

    # Navigate: frame -> rootpane -> layeredpane -> contentpane -> desktoppane -> internalframe
    def children(el):
        try:
            return list(el._generate_childs_from_element(el, visible=False))
        except Exception:
            return []

    def info(el):
        try:
            return el.get_element_information()
        except Exception:
            return {}

    def find_internal_frame(el, depth=0):
        if depth > 8:
            return None
        i = info(el)
        role = (i.get("role") or "").lower()
        name = i.get("name") or ""
        if role == "internal frame":
            print(f"  Found internal frame: {name!r} depth={depth}")
            return el
        for kid in children(el):
            result = find_internal_frame(kid, depth+1)
            if result:
                return result
        return None

    frame = find_internal_frame(root)
    if not frame:
        print("No internal frame found!")
        return 1

    print("Looking for push buttons in the dialog...")
    buttons = find_buttons(frame, max_depth=15, target_name=target)
    print(f"Found {len(buttons)} push button(s)")

    match = next((b for b in buttons if target.lower() in b[0].lower()), None)
    if not match:
        match = next((b for b in buttons), None)

    if not match:
        print("No matching button found")
        return 1

    name, el, btn_info = match
    print(f"Clicking: {name!r} at {btn_info.get('bounds')}")
    try:
        el.click()
        print("Click dispatched via JAB!")
        return 0
    except Exception as e:
        print(f"Click error: {e}")
        return 1

if __name__ == "__main__":
    sys.exit(main())
