import os
import yaml
import uuid

# create an empty dictionary to store the demand tags
demand_tags = {} # demand tags with demands
world_tags = {} # available resources tags with resources available
commoditys = {} # commoditys by name
productions = {} # list of production rules by commodity name
productions_id_map={}
productions_uses = {} # list of productions that are a key commodity 
data={}
def search_yaml_files(directory = "db"):
    """
    Load all tags from the db
    """
    # iterate through the YAML files in the directory
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)
        if os.path.isdir(filepath):
            search_yaml_files(filepath)
        elif filename.endswith(".yml"):
            # open and read the YAML file
            with open(filepath, 'r') as file:
                data = yaml.safe_load(file)
                # check the kind of tag
                if data['kind'] == "world":
                    for tag in data['spec']:
                        world_tags[tag['name']] = tag['res']
                elif data['kind'] == "demand":
                    for tag in data['spec']:
                        demand_tags[tag['name']] = tag['res']
                elif data['kind'] == "commodity":
                    for comm in data['spec']:
                        commoditys[comm['name']] = comm
                elif data['kind'] == "production":
                    for comm in data['spec']:
                        comm["id"]=uuid.uuid4()
                        if comm['name'] not in productions:
                            productions[comm['name']]=[]
                        productions[comm['name']].append(comm)
                        productions_id_map[comm["id"]]=comm
                        for comp in comm["prod"]:
                            k=list(comp.keys())[0]
                            if k not in productions_uses:
                                productions_uses[k]=[]
                            productions_uses[k].append(comm)


