#! /usr/bin/env python
"""Rectangle compression workflow

Requires the following ``SConscript(..., exports={})``

* ``env`` - The SCons construction environment with the following required keys

  * ``modsim_package_abspath`` - Absolute path to the project package
  * ``solve_cpus`` - Integer number of cpus to use in the Abaqus solve task
  * ``datacheck_alias`` - String for the alias collecting the datacheck workflow targets
  * ``regression_alias`` - String for the alias collecting the regression workflow targets
  * ``abaqus`` - String path for the Abaqus executable

* ``alias`` - The workflow name alias root
* ``parameters`` - The current simulation parameter set
"""
import inspect
import pathlib

# Inherit the parent construction environment
Import("env", "alias", "parameters")

# Set project-wide paths with os-agnostic path separators
modsim_package_abspath = env["modsim_package_abspath"]

# Collect the target nodes to build concise target alias(es)
workflow_file = pathlib.Path(inspect.getfile(lambda: None))
artifacts = [str(workflow_file)]
datacheck = []
images = []
workflow = []

# Rectangle part
artifacts.extend(
    SConscript(
        "rectangle",
        exports={"env": env, "parameters": parameters},
    )
)

# SolverPrep
artifacts.extend(
    env.CopySubstfile(
        [modsim_package_abspath / "rectangle_compression.inp.in"],
        substitution_dictionary=env.SubstitutionSyntax(parameters),
    )
)

# Part images
script_options = (
    "--input-file ${SOURCES[1].abspath} --output-file ${TARGET.file} --model-name ${model} --part-name ${model}"
)
images.extend(
    env.AbaqusJournal(
        target=["rectangle_compression.png"],
        source=["export_abaqus_image.py", "rectangle_compression.inp"],
        subcommand_options=script_options,
        model="rectangle",
    )
)

# Abaqus Solve
abaqus_options = "-double both"

datacheck.extend(
    env.AbaqusDatacheck(
        target=["rectangle_compression_DATACHECK.odb"],
        source=["rectangle_compression.inp"],
        job="rectangle_compression_DATACHECK",
        program_options=f"{abaqus_options} -datacheck",
    )
)

standard_extensions = ("odb", "dat", "msg", "com", "prt", "sta")
artifacts.extend(
    env.AbaqusStandard(
        target=["rectangle_compression.odb"],
        source=["rectangle_compression.inp"],
        job="rectangle_compression",
        program_options="${abaqus_options} -cpus $(${solve_cpus}$)",
        abaqus_options=abaqus_options,
        solve_cpus=env["solve_cpus"],
    )
)

# Abaqus Extract
extract_source_list = ["rectangle_compression.odb"]
artifacts.extend(
    env.AbaqusExtract(
        target=["rectangle_compression.h5"],
        source=extract_source_list,
    )
)

# Post-processing
plot_name = "stress_strain_comparison"
post_processing_source = ["rectangle_compression_datasets.h5"]
script_options = "--input-file ${post_processing_source}"
script_options += f" --output-file ${{TARGET.file}} --x-units 'mm/mm' --y-units 'MPa'"
workflow.extend(
    env.PythonScript(
        target=[f"{plot_name}.pdf", f"{plot_name}.csv"],
        source=[modsim_package_abspath / "post_processing.py"] + post_processing_source,
        subcommand_options=script_options,
        post_processing_source=post_processing_source,
    )
)
artifacts.extend(workflow)

# Collector alias(es)
env.Alias(env["regression_alias"], datacheck)
env.Alias(env["datacheck_alias"], datacheck)
env.Alias(f"{alias}-datacheck", datacheck)
env.Alias(f"{alias}-images", images)
env.Alias(alias, workflow)

if not env["unconditional_build"] and not env["ABAQUS_PROGRAM"]:
    print(f"Program 'abaqus' was not found in construction environment. Ignoring '{alias}' target(s)")
    Ignore([".", alias], workflow)
    Ignore([".", f"{alias}-images"], images)
    Ignore([".", env["datacheck_alias"], env["regression_alias"], f"{alias}-datacheck"], datacheck)

Return("artifacts")
