"""Find and click a Java Swing element by name/role using JAB, bypassing Win32 focus."""
import sys
import time
import json

# JAB only works with 32-bit Python (the WindowsAccessBridge-32.dll requirement)
# This script runs through the 32-bit Python via the daemon's pyjab import

import requests

HOST = "http://127.0.0.1:8765"
MAX_NODES = 1500

def main():
    action = sys.argv[1] if len(sys.argv) > 1 else "click"
    target = sys.argv[2] if len(sys.argv) > 2 else "Add"

    print(f"Action: {action}, Target: {target!r}")

    # First try with current cache
    r = requests.get(f"{HOST}/find?text={target}", timeout=10)
    hits = r.json() if r.ok else []

    push_buttons = [h for h in hits if 'push button' in h.get('role', '').lower() or 'push button' in h.get('role_en_us', '').lower()]

    if not push_buttons:
        print(f"Not found in cache (cache has {len(hits)} hits but no push buttons). Refreshing...")
        resp = requests.post(f"{HOST}/refresh", json={"max_depth": 12, "max_nodes": MAX_NODES}, timeout=180)
        print(f"Refresh: {resp.json()}")

        r = requests.get(f"{HOST}/find?text={target}", timeout=10)
        hits = r.json() if r.ok else []
        push_buttons = [h for h in hits if 'push button' in h.get('role', '').lower() or 'push button' in h.get('role_en_us', '').lower()]

    print(f"Found {len(hits)} matching nodes, {len(push_buttons)} push buttons")
    for h in push_buttons[:5]:
        print(f"  id={h.get('id')} name={h.get('name')!r} role={h.get('role')} bounds={h.get('bounds')} enabled={h.get('enabled')}")

    if not push_buttons:
        print("No push button found. All hits:")
        for h in hits[:10]:
            print(f"  id={h.get('id')} name={h.get('name')!r} role={h.get('role')} enabled={h.get('enabled')}")
        return 1

    # Click the first enabled push button
    btn = next((b for b in push_buttons if b.get('enabled')), push_buttons[0])
    print(f"Clicking id={btn['id']} name={btn['name']!r}")

    resp = requests.post(f"{HOST}/click", json={"id": btn["id"]}, timeout=15)
    print(f"Click result: {resp.status_code} {resp.text}")
    return 0

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