import os import json from dotenv import load_dotenv load_dotenv() file_path = os.getenv("FILE_PATH") + "/checklist.md" if os.getenv("FILE_PATH") else "./checklist.md" def read_json() -> dict: try: with open("./src/json/ingredients.json", "rt") as file: return json.load(file) except: print("Could not find or read file.") return {} def update_json(meals: dict) -> None: try: with open("./src/json/ingredients.json", "w") as file: json.dump(meals, file, indent=4) except Exception as e: print(f"Unable to write data to file. {e}") def get_selected_meals(meals: dict) -> dict: meal_json = read_json() selected_meals = {} if meal_json: for meal in meals: if meal in meal_json: selected_meals[meal] = meal_json[meal] return selected_meals def combine_ingredients(meals: dict) -> dict: combined_ingredients = {} for meal, ingredients in meals.items(): for ingredient, detail in ingredients.items(): if ingredient in combined_ingredients: combined_ingredients[ingredient]['quantity'] = str(float(combined_ingredients[ingredient]['quantity']) + float(detail['quantity'])) else: combined_ingredients[ingredient] = detail return combined_ingredients def write_checklist(data: dict) -> None: try: with open(file_path, 'w') as checklist: for ingredient, details in data.items(): s = ingredient + " - " + str(details['quantity']) if details['units'] != None: s += " " + details['units'] checklist.write(f"- [ ] {s}\n") except Exception as e: print(f"Unable to write data to file. {e}") if __name__ == "__main__": meals = read_json() if meals: combined_ingredients = combine_ingredients(meals) write_checklist(combined_ingredients)