import os, subprocess, json

exePath = r"C:/Program Files/nTopology/nTopology/nTopCL.exe"
nTopFilePath = r"BoxPython.ntop"

# Five unique (Length, Width, Height) combinations, in mm
box_dimensions = [
    (2.0, 2.0, 2.0),
    (3.0, 2.0, 4.0),
    (5.0, 1.5, 2.5),
    (1.0, 4.0, 3.0),
    (4.5, 4.5, 1.0),
]

base_output_dir = r"C:\nTopCL_Basics\BoxExamplePython"

for i, (length, width, height) in enumerate(box_dimensions, start=1):
    # Give each run its own output folder and its own input/output JSON files
    # so results from different combinations don't overwrite each other.
    run_output_dir = os.path.join(base_output_dir, f"run_{i}")
    os.makedirs(run_output_dir, exist_ok=True)

    Input_File_Name = os.path.join(run_output_dir, f"inputs_{i}.json")
    Output_File_Name = os.path.join(run_output_dir, f"outputs_{i}.json")

    Inputs_JSON = {
        "description": "This workflow generates a box with changable input length, width, and height, and output directory. It outputs the calculated surface area of the box and exports its stl file as well as a text file",
        "inputs": [
            {
                "description": "",
                "name": "Output directory",
                "type": "text",
                "value": run_output_dir
            },
            {
                "description": "",
                "name": "Length",
                "type": "real",
                "units": "mm",
                "value": length
            },
            {
                "description": "",
                "name": "Width",
                "type": "real",
                "units": "mm",
                "value": width
            },
            {
                "description": "",
                "name": "Height",
                "type": "real",
                "units": "mm",
                "value": height
            }
        ],
        "title": "Box Python Example"
    }

    with open(Input_File_Name, 'w') as outfile:
        json.dump(Inputs_JSON, outfile, indent=4)

    Arguments = [exePath, "-j", Input_File_Name, "-o", Output_File_Name, nTopFilePath]
    print(f"\nRun {i}: Length={length}mm, Width={width}mm, Height={height}mm")
    output, error = subprocess.Popen(Arguments, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
    print(output.decode("utf-8"))
    if error:
        print("Errors:", error.decode("utf-8"))