#!/usr/bin/env python
import argparse
import os
import sys
from pprint import pprint

import meshroom
meshroom.setupEnvironment()

import meshroom.core.graph

parser = argparse.ArgumentParser(description='Query the status of nodes in a Graph of processes.')
parser.add_argument('graphFile', metavar='GRAPHFILE.mg', type=str,
                    help='Filepath to a graph file.')
parser.add_argument('--node', metavar='NODE_NAME', type=str,
                    help='Process the node alone.')
parser.add_argument('--toNode', metavar='NODE_NAME', type=str,
                    help='Process the node and all previous nodes needed.')
parser.add_argument("--verbose", help="Print full status information",
                    action="store_true")

args = parser.parse_args()

if not os.path.exists(args.graphFile):
    print(f'ERROR: No graph file "{args.node}".')
    sys.exit(-1)

graph = meshroom.core.graph.loadGraph(args.graphFile)

graph.update()

if args.node:
    node = graph.node(args.node)
    if node is None:
        print(f'ERROR: node "{args.node}" does not exist in file "{args.graphFile}".')
        sys.exit(-1)
    for chunk in node.chunks:
        print(f'{chunk.name}: {chunk.status.status.name}')
    if args.verbose:
        print('statusFile: ', node.statusFile)
        pprint(node.status.toDict())
else:
    startNodes = None
    if args.toNode:
        startNodes = [graph.findNode(args.toNode)]
    nodes, edges = graph.dfsOnFinish(startNodes=startNodes)
    for node in nodes:
        for chunk in node.chunks:
            print(f'{chunk.name}: {chunk.status.status.name}')
    if args.verbose:
        pprint([n.status.toDict() for n in nodes])
