#! /usr/bin/env python
"""Rectangle compression workflow: geometry, partition, mesh

Requires the following ``SConscript(..., exports=[])``

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

  * ``cubit_source_abspath`` - String absolute path to the EABM's Cubit journal files
  * ``unconditional_build`` - Boolean flag to force building of conditionally ignored targets
  * ``cubit`` - String path for the Cubit executable

* ``element_type`` - The Cubit 4 node quadrilateral element type
* ``solver`` - The target solver to use when writing a mesh file

Returns the following variables

* ``workflow`` - list of targets in the cubit workflow
* ``mesh_files`` - list of orphan mesh file(s)
"""

import pathlib

import waves

# Inherit the parent construction environment
Import('env', "element_type", "solver")

# Set project-wide paths with os-agnostic path separators
cubit_source_abspath = pathlib.Path(env["cubit_source_abspath"])

# Simulation variables
build_directory = pathlib.Path(Dir('.').abspath)
workflow_name = build_directory.name
model = "rectangle"

# Collect the target nodes to build a concise alias for all targets
workflow = []
mesh_files = []

# Geometry
journal_file = f"{model}_geometry"
journal_options = ""
workflow.extend(env.PythonScript(
    target=[f"{journal_file}.cub"],
    source=[f"{cubit_source_abspath / journal_file}.py"],
    script_options=journal_options
))

# Partition
journal_file = f"{model}_partition"
journal_options = ""
workflow.extend(env.PythonScript(
    target=[f"{journal_file}.cub"],
    source=[f"{cubit_source_abspath / journal_file}.py", f"{model}_geometry.cub"],
    script_options=journal_options
))

# Mesh
if solver.lower() == "abaqus":
    mesh_extension = "inp"
elif solver.lower() in ["sierra", "adagio"]:
    mesh_extension = "g"
else:
    raise RuntimeError(f"Unknown solver '{solver}'")
journal_file = f"{model}_mesh"
journal_options = "--element-type ${element_type} --solver ${solver}"
mesh_targets = env.PythonScript(
    target=[f"{journal_file}.{mesh_extension}", f"{journal_file}.cub"],
    source=[f"{cubit_source_abspath / journal_file}.py", f"{model}_partition.cub"],
    script_options=journal_options,
    element_type=element_type,
    solver=solver
)
workflow.extend(mesh_targets)
mesh_files.extend(mesh_targets[0:2])

# Collector alias based on parent directory name
env.Alias(f"{workflow_name}_cubit", workflow)

if not env['unconditional_build'] and not env['cubit']:
    print(f"Program 'cubit' was not found in construction environment. Ignoring '{workflow_name}' target(s)")
    Ignore(['.', workflow_name], workflow)

Return(["workflow", "mesh_files"])
