import os
import random
import subprocess

def create_instances(
    n_instances=50,
    cocktails_range=(1, 3),     # e.g., choose cocktails from [1..3]
    ingredients_range=(2, 4),   # e.g., choose ingredients from [2..4]
    shots_range=(3, 7),         # e.g., choose shots from [3..7]
    seed_range=(1, 99999),      # range of possible random seeds
):
    """
    Creates n_instances Barman problem files in a folder called 'instances'.
    Each problem is named 'instance-{i}.pddl'.

    You can tune the ranges (cocktails_range, ingredients_range, shots_range)
    and the seed_range as you wish.
    """
    # Make the output folder if it does not exist
    os.makedirs("instances", exist_ok=True)

    for i in range(1, n_instances + 1):
        # Randomly pick how many cocktails, ingredients, and shots
        num_cocktails = random.randint(cocktails_range[0], cocktails_range[1])
        num_ingredients = random.randint(ingredients_range[0], ingredients_range[1])
        # Shots must be at least (num_cocktails + 1) to satisfy the script’s constraint:
        min_shots = max(shots_range[0], num_cocktails + 1)
        max_shots = shots_range[1]
        if min_shots > max_shots:
            # If the user-supplied ranges are inconsistent, we can skip or break:
            print(f"Cannot find a valid #shots for instance {i} (cocktails={num_cocktails}). Skipping.")
            continue
        num_shots = random.randint(min_shots, max_shots)

        # Choose a random seed
        seed = random.randint(seed_range[0], seed_range[1])

        # Construct output file name
        output_filename = f"instances/instance-{i}.pddl"
        print(
            f"Generating instance {i} with "
            f"cocktails={num_cocktails}, ingredients={num_ingredients}, shots={num_shots}, seed={seed} "
            f"-> {output_filename}"
        )

        # Call the original barman_generator.py as a subprocess
        # Make sure barman_generator.py is in the same folder or provide its path.
        cmd = [
            "python",              # Or "python3", depending on your environment
            "barman-generator.py", # Replace with the actual path if needed
            str(num_cocktails),
            str(num_ingredients),
            str(num_shots),
            str(seed)
        ]

        with open(output_filename, "w") as outfile:
            subprocess.run(cmd, stdout=outfile, check=True)


if __name__ == "__main__":
    # Example usage with default parameters (50 instances):
    create_instances(
        n_instances=50,
        cocktails_range=(2, 2),
        ingredients_range=(2, 2),
        shots_range=(2, 3),
        seed_range=(1, 99999)
    )
