#! /usr/bin/env python
"""quickstart report workflow

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

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

  * ``project_dir`` - String absolute path to the EABM project root directory
  * ``documentation_abspath`` - String absolute path to the EABM HTML documentation source files
  * ``sphinx_build`` - String path for the Sphinx build executable
"""

import pathlib

import waves

# Inherit the parent construction environment
Import(["env", "project_variables"])

# Set empty workflow list
report = []

# Perform variable substitution on Sphinx configuration file
report.extend(env.Substfile(
    "conf.py.in",
    SUBST_DICT=waves.scons_extensions.substitution_syntax(project_variables)))

# Copy project root files required by the documentation
project_dir = pathlib.Path(env["project_dir"])
root_files = [("README.txt", str(project_dir / "README.rst"))]
for target, source in root_files:
    report.extend(env.Command(
        target=[target],
        source=[source],
        action=Copy("$TARGET", "$SOURCE")))

# Copy documentation source files re-used in the report
documentation_abspath = pathlib.Path(env["documentation_abspath"])
report_copy_list = [
    documentation_abspath / "nominal.rst",
    documentation_abspath / "project_brief.txt",
    documentation_abspath / "zreferences.rst",
    documentation_abspath / "references.bib",
    documentation_abspath / "targets.txt",
    documentation_abspath / "simulation_description.txt",
    documentation_abspath / "simulation_description_short.txt",
    documentation_abspath / "simulation_material.txt",
    documentation_abspath / "rectangle_schematic.png",
    documentation_abspath / "stress_strain_comparison.png",
    documentation_abspath / "theory.txt",
    documentation_abspath / "mesh_convergence.rst",
    documentation_abspath / "mesh_convergence_stress.png",
    documentation_abspath / "mesh_convergence_conclusions.txt",
    documentation_abspath / "nominal_conclusions.txt",
]
report_copy_list = [pathlib.Path(source_file) for source_file in report_copy_list]
report.extend(waves.scons_extensions.copy_substitute(
    report_copy_list,
    substitution_dictionary=waves.scons_extensions.substitution_syntax(project_variables)))

# PDF Report build task
report_source_list = ["index.rst"] + [source_file.name.rstrip(".in") for source_file in report_copy_list]
report_directory = Dir("latex")
sphinx_options = "-W"
report.extend(env.Command(
    target=[report_directory],
    source=report_source_list,
    action=f"{env['sphinx_build']} -M latexpdf ${{TARGET.dir.abspath}} ${{TARGET.dir.abspath}} ${{sphinx_options}}",
    sphinx_options=sphinx_options
))
env.AlwaysBuild(report)
env.Clean(report, report_directory)

# Collector alias to build the PDF report
parent_directory = Dir(".").srcnode().name
env.Alias(parent_directory, report)
