import json
from collections import OrderedDict


class Node:
	name = None
	dependencies = []

	def __init__(self, name, dependencies):
		self.name = name
		self.dependencies = dependencies


g = Node('g', [])
f = Node('f', [])
e = Node('e', [])
d = Node('d', [])
c = Node('c', [])
b = Node('b', [f, g])
a = Node('a', [b, c, d])
f.dependencies.append(a)

# This looks like this:
#  _________
# /         v
# |      __ A __
# |     /   |   \
# |    v    v    v
# |    B    C    D
# |   / \
# |  v   v
# \--F   G
#
# Note that there is a dependency loop from A -> B -> F -> A
# but it will be handled in the final dependency tree.


def build_dependency_tree(curr_node, visited=set()):
	# Using OrderedDict just for printing nicely at the end, can use {} in real-life
	graph_from_here = OrderedDict()
	graph_from_here['name'] = curr_node.name,
	graph_from_here['dependencies'] = []

	if curr_node in visited:
		return graph_from_here
	else:
		visited.add(curr_node)

	for dependency_node in curr_node.dependencies:
		graph_from_here['dependencies'].append(build_dependency_tree(dependency_node, visited))

	return graph_from_here


print(json.dumps(build_dependency_tree(a), indent=2))

