#! /usr/bin/env python
import waves

Import("env")

# Collect the target nodes to build concise target alias(es)
artifacts = []
workflow = []

# Geometry, Partition, Mesh
artifacts.extend(
    env.PythonScript(
        target=["rectangle_gmsh.inp"],
        source=["rectangle.py"],
        subcommand_options="--output-file=${TARGET.abspath}",
        action_suffix=env["action_suffix"],
    )
)

artifacts.extend(
    env.PythonScript(
        target=["rectangle_mesh.inp"],
        source=["strip_heading.py", "rectangle_gmsh.inp"],
        subcommand_options="--input-file=${SOURCES[1].abspath} --output-file=${TARGET.abspath}",
        action_suffix=env["action_suffix"],
    )
)

# CalculiX Solve
artifacts.extend(
    env.CalculiX(
        target=[f"rectangle_compression.{suffix}" for suffix in ("frd", "dat", "sta", "cvg", "12d")],
        source=["rectangle_compression.inp"],
        action_suffix=env["action_suffix"],
    )
)

# Extract
artifacts.extend(
    env.Command(
        target=["rectangle_compression.vtu", "rectangle_compression.vtu.stdout"],
        source=["rectangle_compression.frd"],
        action=["cd ${TARGET.dir.abspath} && ccx2paraview ${SOURCES[0].abspath} vtu ${action_suffix}"],
        action_suffix=env["action_suffix"],
    )
)
workflow.extend(
    env.PythonScript(
        target=["rectangle_compression.h5"],
        source=["vtu2xarray.py", "rectangle_compression.vtu"],
        subcommand_options="--input-file ${SOURCES[1].abspath} --output-file ${TARGET.abspath}",
        action_suffix=env["action_suffix"],
    )
)

# Post-processing
script_options = "--input-file ${SOURCES[1:].abspath}"
script_options += " --output-file ${TARGET.file} --x-units mm/mm --y-units MPa"
workflow.extend(
    env.PythonScript(
        target=["stress_strain_comparison.pdf", "stress_strain_comparison.csv"],
        source=["post_processing.py", "rectangle_compression.h5"],
        subcommand_options=script_options,
    )
)
artifacts.extend(workflow)

# Collector alias named after the model simulation
env.Alias("rectangle", workflow)

if not env["unconditional_build"] and (not env["CCX_PROGRAM"] or not env["ccx2paraview"]):
    print(
        "Program 'CalculiX (ccx)' or 'ccx2paraview' was not found in construction environment. "
        "Ignoring 'rectangle' target(s)"
    )
    Ignore([".", "rectangle"], workflow + artifacts)
