#! /usr/bin/env python
# __author__ = "Parisa Kianmajd"
#__version__ = "1.0.1"

# graph homomorphism

import sys
import subprocess
import yaml


nodes = {}
isaedges = {}
elements = dict()

def compose_edge(s,t,label):
        edge = {}
        edge.update({"s" : s})
        edge.update({"t" : t})
        edge.update({'label' : label})
        return edge
def add_node(concept, group):
        node = {}
        node.update({'concept': concept})
        node.update({'group': group})
        if group!='(+)':
            nodes.update({group + "." + concept: node})
        else:
            nodes.update({concept: node})

com = 'dlv -silent homomorphism_code.dlv' + " " + sys.argv[1] + " " + sys.argv[2] + ' -filter=g1,g2,in'
proc = subprocess.Popen(com, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
lst = out.strip().split("\n")
rules = list()
for d in lst:
    rules.append(d[d.find("{")+1:d.find("}")].split(", "))
for r in rules[0]:
    if r.startswith("g"):
        start, end = r[r.find("(")+1:r.find(")")].split(",")
        pair = r[:2] + "(" + end + "," + start + ")"
        group = r[1]
        label = 'isa'
        if group not in elements:
                elements.update({group:set()})
        for e in [start,end]:
                elements[group].add(e)
        add_node(start, group)
        add_node(end, group)
        start = group + "." + start
        end = group + "." + end
        isaedges.update({start + "_" + end: compose_edge(start,end, label)})
        if pair in rules[0]:
                rules[0].remove(pair)
pw = 1
for rule in rules:
    edges = {}
    for r in rule:
        if r.startswith('in'):
                start, end = r[r.find("(")+1:r.find(")")].split(",")
                label = 'map'
                for d in elements:
                        if start in elements[d]:
                                start = d + "." + start
                        if end in elements[d]:
                                end = d + "." + end
                edges.update({start + "_" + end: compose_edge(start,end,label)})
    edges.update(isaedges)
    outfile = open('pw' + str(pw) + '.yaml', "w")
    yaml.dump(nodes, outfile, default_flow_style=False)
    yaml.dump(edges, outfile, default_flow_style=False)
    outfile.close()
    pw += 1