"""
Simple script to visualize tags.json using Graphviz.
"""

import json
import subprocess

with open("./tags.json", mode="r", encoding="UTF-8") as f:
    json_data = json.load(f)


def slug(s):
    ret = ""
    for c in s.lower():
        if ord(c) >= ord("a") and ord(c) <= ord("z"):
            ret += c
        else:
            ret += "_"

    return ret


def traverse(node):
    s = slug(node["tag"])
    out = f'    {s} [label="{node["tag"]}"];\n'
    out_e = ""
    for child in node["children"]:
        out_e += f'    {s} -> {slug(child["tag"])};\n'
        o, e = traverse(child)
        out += o
        out_e += e

    return out, out_e


out, out_e = "digraph tags {\n", ""

o, e = traverse(json_data)
out += o
out_e += e

out += "\n" + out_e + "}\n"

with open("./tagviz.gv", mode="w", encoding="UTF-8") as f:
    f.write(out)

subprocess.run(["dot", "-Tsvg", "-O", "-Kdot", "./tagviz.gv"], check=True)
