#! /usr/bin/env python
"""quickstart documentation 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
  * ``sphinx_build`` - String path for the Sphinx build executable
"""

import os
import pathlib

import waves

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

# Set empty alias return list
alias_list = []

# Perform variable substitution on Sphinx configuration file
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")),
              ("environment.yml", str(project_dir / "environment.yml"))]
for target, source in root_files:
    env.Command(
        target=[target],
        source=[source],
        action=Copy("$TARGET", "$SOURCE"))

# Explicit Sphinx documentation dependency list
documentation_file_list = [
    "conf.py",
    "api.rst",
    "cli.rst",
    "changelog.rst",
    "devops.rst",
    "glossary.rst",
    "index.rst",
    "mesh_convergence.rst",
    "nominal.rst",
    "release_philosophy.rst",
    "simulation_summary.rst",
    "user.rst",
    "zreferences.rst",
    # Found in conf.py, which is not scanned for implicit dependencies
    "waves_logo_brandmark_smaller.png",
    'targets.txt',
    "_static/custom.css"
]

html_directory = Dir("html")
sphinx_options = "-W"
html = env.Command(
    target=[html_directory],
    source=documentation_file_list,
    action=f"{env['sphinx_build']} ${{sphinx_options}} -b html ${{TARGET.dir.abspath}} ${{TARGET.dir.abspath}}{os.sep}html",
    sphinx_options=sphinx_options)
env.Clean(html, html_directory)
env.AlwaysBuild(html)
alias_list.extend(env.Alias("html", html))

latex_directory = Dir("latex")
latexpdf = env.Command(
    target=[latex_directory],
    source=documentation_file_list,
    action=f"{env['sphinx_build']} -M latexpdf ${{TARGET.dir.abspath}} ${{TARGET.dir.abspath}} ${{sphinx_options}}",
    sphinx_options=sphinx_options
)
env.Clean(latexpdf, latex_directory)
env.AlwaysBuild(latexpdf)
alias_list.extend(env.Alias("latexpdf", latexpdf))

# Collector alias to build all documentation
alias_list.extend(env.Alias("documentation", html + latexpdf))

if not env["sphinx_build"]:
    print(f"Program 'sphinx-build' was not found in construction environment. Ignoring Sphinx target(s)")
    Ignore([".", "html", "html"], html)
    Ignore([".", "latex", "latexpdf"], latexpdf)
else:
    env.Default(html)

# Return the alias list to SConstruct for help message output
Return("alias_list")
