Python
import random
import threading


class RecipeGenerator:
    """
    Generates recipes based on provided ingredients and dietary requirements.

    The class stores a dictionary of recipes categorized by dietary requirements
    (vegetarian, vegan, gluten-free). It provides methods to generate a
    random recipe matching the given criteria, list supported ingredients and
    dietary requirements. Thread safety is implemented to handle concurrent
    recipe generation.
    """

    def __init__(self):
        """
        Initializes the RecipeGenerator with a predefined set of recipes.
        """
        self.recipes = {
            "vegetarian": [
                {"name": "Vegetable Stir Fry", "ingredients": ["broccoli", "carrot", "bell pepper", "onion", "tofu", "soy sauce"],
                    "instructions": "1. Heat oil in a pan. 2. Add chopped vegetables and tofu. 3. Stir in soy sauce and cook until tender."},
                {"name": "Caprese Salad", "ingredients": ["tomato", "mozzarella cheese", "basil", "balsamic vinegar", "olive oil"],
                    "instructions": "1. Slice tomatoes and mozzarella. 2. Arrange on a plate with basil leaves. 3. Drizzle with olive oil and balsamic vinegar."},
                {"name": "Vegetarian Chili", "ingredients": ["black beans", "kidney beans", "bell pepper", "onion", "tomato", "chili powder"],
                    "instructions": "1. Saute onions and bell peppers. 2. Add tomatoes and beans. 3. Season with chili powder and cook until thickened."}
            ],
            "vegan": [
                {"name": "Vegan Curry", "ingredients": ["coconut milk", "chickpeas", "potato", "carrot", "curry powder", "onion"],
                    "instructions": "1. Cook onions, carrots, and potatoes until tender. 2. Add chickpeas and coconut milk. 3. Simmer with curry powder."},
                {"name": "Quinoa Salad", "ingredients": ["quinoa", "cucumber", "tomato", "red onion", "lemon juice", "olive oil"],
                    "instructions": "1. Cook quinoa according to package instructions. 2. Mix with chopped vegetables. 3. Dress with lemon juice and olive oil."},
                {"name": "Vegan Pasta Primavera", "ingredients": ["pasta", "zucchini", "bell pepper", "cherry tomatoes", "garlic",
                                                                  "olive oil"], "instructions": "1. Cook pasta until al dente. 2. Saute vegetables in olive oil. 3. Toss with cooked pasta."}
            ],
            "gluten-free": [
                {"name": "Grilled Salmon with Asparagus", "ingredients": ["salmon fillet", "asparagus", "lemon", "olive oil", "salt", "pepper"],
                    "instructions": "1. Season salmon with salt and pepper. 2. Grill until cooked through. 3. Serve with grilled asparagus and lemon wedges."},
                {"name": "Quinoa Stuffed Bell Peppers", "ingredients": ["bell peppers", "quinoa", "black beans", "corn", "tomato", "avocado"],
                    "instructions": "1. Cook quinoa according to package instructions. 2. Mix with beans, corn, and diced tomato. 3. Stuff mixture into halved bell peppers and bake until tender."},
                {"name": "Gluten-Free Banana Pancakes", "ingredients": ["banana", "egg", "oat flour", "almond milk", "vanilla extract", "baking powder"],
                    "instructions": "1. Mash bananas and mix with egg, oat flour, almond milk, and vanilla extract. 2. Stir in baking powder. 3. Cook pancakes on a hot griddle until golden brown."}
            ]
        }
        self.lock = threading.Lock()

    def _get_filtered_recipes(self, ingredients, dietary_requirements):
        """
        Filters recipes based on ingredients and dietary requirements.

        Args:
            ingredients (list): A list of ingredients to filter by.
            dietary_requirements (str): The dietary requirement (e.g., "vegetarian").

        Returns:
            list: A list of recipes matching the criteria.
        """
        return [recipe for recipe in self.recipes[dietary_requirements] if all(ingredient in recipe["ingredients"] for ingredient in ingredients)]

    def generate_recipe(self, ingredients, dietary_requirements):
        """
        Generates a random recipe based on ingredients and dietary requirements.

        Args:
            ingredients (list): A list of ingredients.
            dietary_requirements (str): The dietary requirement.

        Returns:
            dict or str: A randomly chosen recipe (dictionary) if found,
                         or a string message if no recipe is found or the
                         dietary requirement is invalid.

        Raises:
            KeyError: If the provided dietary requirement is not in the recipe database.
        """
        with self.lock:  # Ensures thread-safe access to the recipes dictionary.
            try:
                filtered_recipes = self._get_filtered_recipes(
                    ingredients, dietary_requirements)
                if filtered_recipes:
                    return random.choice(filtered_recipes)
                else:
                    return "No recipe found with the given ingredients and dietary requirements."
            except KeyError:
                return "Invalid dietary requirement provided."

    def supported_ingredients(self):
        """
        Returns a set of all unique ingredients supported by the recipe generator.

        Returns:
            set: A set of supported ingredient strings.
        """
        return set(ingredient for recipe_set in self.recipes.values() for recipe in recipe_set for ingredient in recipe["ingredients"])

    def supported_dietary_requirements(self):
        """
        Returns a list of supported dietary requirements.

        Returns:
            list: A list of the supported dietary requirement strings.
        """
        return list(self.recipes.keys())


def main():
    generator = RecipeGenerator()
    print("Supported Ingredients:", generator.supported_ingredients())
    print("Supported Dietary Requirements:",
          generator.supported_dietary_requirements())

    ingredients = ["tofu", "broccoli", "bell pepper", "soy sauce"]
    dietary_requirements = "vegetarian"
    try:
        recipe = generator.generate_recipe(ingredients, dietary_requirements)
        if isinstance(recipe, dict):
            print("\nGenerated Recipe:")
            print("Name:", recipe["name"])
            print("Ingredients:", ", ".join(recipe["ingredients"]))
            print("Instructions:")
            print(recipe["instructions"])
        else:
            print(recipe)
    except Exception as e:
        print(f"An error occurred: {e}")


if __name__ == "__main__":
    main()
Supported Ingredients: {'zucchini', 'pepper', 'mozzarella cheese', 'black beans', 'potato', 'coconut milk', 'cucumber', 'basil', 'red onion', 'olive oil', 'vanilla extract', 'tomato', 'curry powder', 'banana', 'bell peppers', 'quinoa', 'avocado', 'chili powder', 'salmon fillet', 'broccoli', 'cherry tomatoes', 'salt', 'tofu', 'lemon', 'soy sauce', 'chickpeas', 'carrot', 'corn', 'egg', 'lemon juice', 'oat flour', 'pasta', 'garlic', 'asparagus', 'balsamic vinegar', 'onion', 'almond milk', 'bell pepper', 'kidney beans', 'baking powder'}
Supported Dietary Requirements: ['vegetarian', 'vegan', 'gluten-free']

Generated Recipe:
Name: Vegetable Stir Fry
Ingredients: broccoli, carrot, bell pepper, onion, tofu, soy sauce
Instructions:
1. Heat oil in a pan. 2. Add chopped vegetables and tofu. 3. Stir in soy sauce and cook until tender.