"""Trace the menu path to Purchase Order Maintenance (node 99) through parent chain."""
import requests

HOST = "http://127.0.0.1:8765"

r = requests.get(f"{HOST}/cache", timeout=10)
rows = r.json()['rows']
id_to_row = {row['id']: row for row in rows}

# Trace from node 99 upward
node = 99
path = []
while node is not None:
    row = id_to_row.get(node)
    if not row:
        path.append(f"[{node}] NOT IN CACHE")
        break
    path.append(f"[{node}] role={row['role']!r} name={row['name']!r} parent={row['parent']}")
    node = row.get('parent')

print("Path from node 99 to root:")
for step in reversed(path):
    print(f"  {step}")

# Find all Finance menu children (show hierarchy)
print("\nFinance menu [23] children:")
def print_subtree(node_id, depth=0):
    row = id_to_row.get(node_id)
    if not row:
        return
    print(f"{'  '*depth}[{node_id}] {row['role']!r:15} {row['name']!r}")
    # Find children
    children = [r for r in rows if r.get('parent') == node_id]
    for child in children:
        print_subtree(child['id'], depth+1)

print_subtree(23)
