
import yaml
import json
import os


def generic_constructor(loader, tag_suffix, node):
    if isinstance(node, yaml.ScalarNode):
        return loader.construct_scalar(node)
    elif isinstance(node, yaml.SequenceNode):
        return loader.construct_sequence(node)
    elif isinstance(node, yaml.MappingNode):
        return loader.construct_mapping(node)

yaml.SafeLoader.add_multi_constructor('!', generic_constructor)

def parse_recipes(directory):

    recipes = []
    
    for filename in os.listdir(directory):
        if filename.endswith(".yml"):
            with open(os.path.join(directory, filename), 'r') as f:
                data = yaml.safe_load(f)
                if data:
                    for item in data:
                        if item.get('type') == 'reaction':
                            recipes.append(item)
    return recipes


def process_recipes(raw_recipes):
    processed = {}
    
    for r in raw_recipes:
        products = r.get('products', {})
        reactants = r.get('reactants', {})
        
        reactant_data = {}
        for k, v in reactants.items():
            if isinstance(v, dict):
                reactant_data[k] = {
                    'amount': v.get('amount', 0),
                    'catalyst': v.get('catalyst', False)
                }
            else:
                reactant_data[k] = {
                    'amount': v,
                    'catalyst': False
                }

        recipe_data = {
            'id': r.get('id'),
            'reactants': reactant_data,
            'products': products,
            'minTemp': r.get('minTemp'),
            'requiredMixerCategories': r.get('requiredMixerCategories'),
            'priority': r.get('priority', 0)
        }

        
        for product_id, product_amount in products.items():
            if product_id not in processed:
                processed[product_id] = []
            processed[product_id].append(recipe_data)
            
    return processed

if __name__ == "__main__":
    raw = parse_recipes('./mixingrecipes')
    processed = process_recipes(raw)
    
    with open('recipes.json', 'w') as f:
        json.dump(processed, f, indent=2)
    print(f"Processed {len(processed)} unique products.")
