import json
import re

def expand_templates(s, templatesA, templatesB):
    while True:
        m = re.search("%[A-Z_]+%", s)
        if (m is None):
            return s
        key = m[0][1:-1].lower()
        repl = templatesA.get(key, templatesB.get(key)) 
        if (repl is None):
            raise IndexError("key {} was not as a template".format(key))
        s = s.replace(m[0], repl)
with open("queries-input.json") as f:
    j = json.load(f)
    target = {}
    for kg in j["statistics"]:
        
        target["statistics-" + kg] = dict()
        target["statistics-" + kg]["query"] = expand_templates(j["templates"]["statistics"],j["statistics"][kg],
        j["templates"])
        target["statistics-" + kg]["kg"] = kg
        target["statistics-" + kg]["kg-name"] = j["statistics"][kg]["kg-name"]
        target["statistics-" + kg]["order"] = j["statistics"][kg]["order"]

    for q in j["queries"]:
        target[q] = j["queries"][q]
            
    print(json.dumps(target, indent=4))
    """

    t = re.sub("%PREFIXES%", j["statistics-dblp"]["prefixes"],
            j["statistics-template"])
    t = re.sub("%CONTENT%", j["statistics-dblp"]["content"], t) 
    t = re.sub("%NUM_PREDICATES%", j["statistics-num-predicates"], t) 
    t = re.sub("%NUM_SUBJECTS%", j["statistics-num-subjects"], t) 
    t = re.sub("%NUM_TRIPLES%", j["statistics-num-triples"], t) 
    t = re.sub("%VALUES%", j["statistics-values"], t) 
    print (t)
    """


