#
# Copyright (c) Daniel Sheffield 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
import re
import yaml
from yaml.loader import SafeLoader
from .data.QueryManager import QueryManager

def parse_recipe(fh, query_manager: QueryManager):
    contents = yaml.load(fh, Loader=SafeLoader)
    recipe = {
        'ingredients': [],
        'feeds': None,
        'instructions': None,
    }
    for ingredient in contents['ingredients']:
        match = re.search(
            r'(?P<product>.*) (?P<quantity>[0-9\.]+) ?(?P<unit>.*)', ingredient
        )
        assert match is not None, f'Could parse {ingredient}'
        units = query_manager.unique_suggestions('unit', unit=match.group('unit'))
        assert match.group('unit') in units, f"Unknown unit: '{match.group('unit')}'"
        recipe['ingredients'].append(
            [match.group('product').strip(), match.group('quantity'), match.group('unit')]
        )
    for k in set(recipe.keys()) - set(['ingredients']):
        if k in contents:
            recipe[k] = contents[k]
    return recipe
