#!/usr/bin/env python3

from __future__ import print_function
import sys
import os
sys.path.append('/usr/share/botch')
from util import read_graphml
import networkx as nx


def extract_scc(g):
    result = []
    for scc in nx.components.strongly_connected_component_subgraphs(g):
        if len(scc) <= 1:
            continue
        result.append(scc)
    return result

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description="Extract strongly " +
                                                 "connected components " +
                                                 "(SCC) from input graph")
    parser.add_argument('graph', metavar='graph.xml',
                        type=read_graphml, help='graph in GraphML format')
    parser.add_argument('prefix', metavar='prefix', nargs='?',
                        default='scc', help="output graph prefix (default: " +
                                            "scc)")
    parser.add_argument('--outdir', metavar='dir', type=str,
                        default=".", help="output directory. Default is " +
                                          "current directory")
    parser.add_argument(
        '-v', '--verbose', action='store_true', help='be verbose')
    args = parser.parse_args()
    res = extract_scc(args.graph)
    for scc in res:
        # get the source node with the lowest name
        m = min((a['name'] for _, a in scc.nodes_iter(data=True)
                if a['name'].startswith('src:')))
        fname = "%s_%s_%d.xml" % (args.prefix, m, len(scc))
        fullfname = os.path.join(args.outdir, fname)
        nx.write_graphml(scc, fullfname)
        print(fname)
