
##############################################################################
#
# Copyright (c) 2003-2026 by the esys.escript Group
# https://github.com/LutzGross/esys-escript.github.io
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# See CREDITS file for contributors and development history
#
##############################################################################

import os
Import('*')

import subprocess

haveMPL=False   # do we have matplotlib?
try:
    with open(os.devnull, 'w') as devnull:
        p = subprocess.call(['python3', '-c', 'import matplotlib'], stdout=devnull, stderr=devnull)
        if p < 1:
           haveMPL=True
except Exception as e:
    haveMPL=False
if not haveMPL:
    env['warnings'].append("matplotlib not found. Testing of some examples will be skipped.")

example_files_allow_mpi = []
example_files_no_mpi = []
example_deps = []
skipped_tests = []
example_metadata = {}  # Store metadata for each example

def sortOutExample(name, needsMPL=False, needsMagicMPL=False, needsGD=False, allowsMPI=True,
                   minMPISize=1, requiresMPI4py=False):
    if needsMagicMPL: needsMPL=True
    if needsGD: needsMPL=True

    # Store metadata for this example
    example_metadata[name] = {
        'minMPISize': minMPISize,
        'requiresMPI4py': requiresMPI4py,
        'needsMPL': needsMPL
    }

    if  (not needsMPL or haveMPL):
        if allowsMPI:
            example_files_allow_mpi.append(name)
        else:
            example_files_no_mpi.append(name)
    else:
        example_deps.append(name)

# these are the release examples in example subdirectory:
#
#_deps is for files which end in .py and are required for
# testing but should not be invoked directly themselves

sortOutExample('usersguide/heatedblock.py')
sortOutExample('usersguide/helmholtz.py')
sortOutExample('usersguide/poisson.py')
sortOutExample('usersguide/diffusion.py')
sortOutExample('usersguide/poisson_vtk.py')
sortOutExample('usersguide/dirac.py')
sortOutExample('usersguide/int_save.py')
sortOutExample('usersguide/wave.py', needsMPL=True)
sortOutExample('usersguide/poisson_matplotlib.py', allowsMPI=False)
sortOutExample('usersguide/lame_matplotlib.py', needsMPL=True, allowsMPI=False)
sortOutExample('usersguide/lame_silo.py')
sortOutExample('usersguide/simpletest.py')
sortOutExample('usersguide/rosenbrock.py', allowsMPI=False)
sortOutExample('usersguide/inclusion.py')
sortOutExample('usersguide/MT.py', allowsMPI=False)
sortOutExample('usersguide/MT_master_slave.py', allowsMPI=True, minMPISize=2, requiresMPI4py=True)
sortOutExample('usersguide/ensemble_example.py', allowsMPI=True, minMPISize=4, requiresMPI4py=True)
sortOutExample('usersguide/thermo_mechanical.py', allowsMPI=True, minMPISize=8, requiresMPI4py=True)
sortOutExample('usersguide/voxet_reader.py', allowsMPI=True)

# Supporting files for examples
example_deps.append('usersguide/simplemesh.msh')      # for simpletest.py
example_deps.append('usersguide/simplemesh.geo')       # Gmsh input
example_deps.append('usersguide/simplemeshfine.geo')   # Gmsh input
example_deps.append('usersguide/inclusion.msh')        # for inclusion.py
example_deps.append('usersguide/inclusion.geo')        # Gmsh input
example_deps.append('usersguide/simplebob.xml')        # XML input
example_deps.append('usersguide/complicatedbob.xml')   # XML input



example_files = example_files_allow_mpi + example_files_no_mpi + example_deps

# wave_examples = ['inversion/synthetic_HTI.py',
#     'inversion/synthetic_VTI.py',
#     'inversion/synthetic_TTI.py',
#     'inversion/synthetic_sonic.py',
#     'inversion/synthetic_sonicHTI.py']

wave_examples = []

for i in wave_examples:
    sortOutExample(i)

ex2=[os.path.join("examples", str(x)) for x in example_files]#+wave_examples]

#=============================================================================

local_env = env.Clone()
src_dir = local_env.Dir('.').srcnode().abspath
release_dir=os.path.join(env['prefix'],'release','doc')
Export('release_dir')

dir_cmd = "cd "+src_dir+" && "

# Need to use explicit tar/zip rather than the builder due to problems getting
# it not to put unwanted path components in the archive file
# --transform on tar is not supported on savanna
zip_path=os.path.join(release_dir, 'escript_examples.zip')
zip = local_env.Command(zip_path, None, dir_cmd+"zip "+zip_path+" "+" ".join(ex2))
env.Alias('examples_zipfile', zip)

tar_path=os.path.join(release_dir, 'escript_examples.tar')
targz_path=os.path.join(release_dir, 'escript_examples.tar.gz')
tar = local_env.Command(tar_path, None, dir_cmd+"tar -cf "+tar_path+" "+" ".join(ex2))
targz = local_env.Command(targz_path, tar, "gzip -n -9 "+tar_path)
env.Alias('examples_tarfile', targz)

# Convert markdown documentation to HTML
md2html_script = os.path.join(src_dir, 'md2html.py')
readme_md = '#/README.md'
installation_md = '#/installation.md'
index_html = os.path.join(release_dir, 'index.html')
installation_html = os.path.join(release_dir, 'installation.html')

# Build index.html from README.md
readme_html = local_env.Command(index_html, [readme_md, md2html_script],
                                'python3 ${SOURCES[1]} readme ${SOURCES[0]} $TARGET')
env.Alias('readme_html', readme_html)

# Build installation.html from installation.md
install_html = local_env.Command(installation_html, [installation_md, md2html_script],
                                 'python3 ${SOURCES[1]} installation ${SOURCES[0]} $TARGET')
env.Alias('installation_html', install_html)

# Note: user.pdf is built directly to release/doc/user/user.pdf by doc/user/SConscript
# No need for a separate copy step

#env=Environment(TARFLAGS = "-c -z",chdir=src_dir)
#if 'Tar' in dir(env):
# tar=env.Tar(tar_path, example_files, chdir=src_dir)
# env.Alias('examples_tarfile', tar)

local_env.SConscript(dirs = ['#/doc/user'], variant_dir='user', duplicate=1)
# Epydoc removed - use Sphinx instead
#local_env.SConscript(dirs = ['#/doc/epydoc'], variant_dir='epydoc', duplicate=1)
local_env.SConscript(dirs = ['#/doc/sphinx_api'], variant_dir='sphinx_api', duplicate=1)
local_env.SConscript(dirs = ['#/doc/doxygen'], variant_dir='doxygen', duplicate=1)
local_env.SConscript(dirs = ['#/doc/examples'], variant_dir='examples', duplicate=1, exports=['example_files_allow_mpi', 'example_files_no_mpi', 'example_deps', 'example_metadata'])
