import os
import os.path
import yaml
from durable.lang import *

def write_facts(ruleset: set):
    facts = get_facts(ruleset)

    types = set((f.get("type") for f in facts))

    print(f"types: {types}")

    out_dir = "out"
    if not os.path.exists(out_dir):
        os.mkdir(out_dir)

    basedir = os.path.join(out_dir, ruleset)
    if os.path.exists(basedir):
        for f in os.listdir(basedir):
            p = os.path.join(basedir, f)
            if os.path.isdir(p):
                for f2 in os.listdir(p):
                    os.remove(os.path.join(p, f2))
                os.rmdir(p)
            else:
                os.remove(p)
        os.rmdir(basedir)
    os.mkdir(basedir)

    for t in types:
        typedir = os.path.join(basedir, t)
        os.mkdir(typedir)

        fs = []
        for fact in facts:
            if fact["type"] != t:
                continue

            if fact["type"] == "meta":
                continue

            if fact.get("key") is None:
                raise Exception(f"Bad fact: no 'key' {fact}")

            try:
                del fact["sid"]
            except KeyError:
                pass

            fs.append(fact)

        i = 0
        for fact in sorted(fs, key=lambda f: f["key"]):
            key = fact["key"]
            path = os.path.join(typedir, f"{key.replace('/', '_')}.yaml")
            with open(path, "w") as f:
                s = yaml.dump(fact)
                f.write(s)
            i = i + 1