
##############################################################################
#
# 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('*')

local=env.Clone()

epy_dir=os.path.join(release_dir, 'sphinx_api')
local.Command(epy_dir, [], [Mkdir(epy_dir)])

int_dir=os.path.join(env['BUILD_DIR'], 'sphinx_int')
local.Command(int_dir, [], [Mkdir(int_dir)])

# Set up environment for genrst.py to import esys modules
# Add PYTHONPATH so Python can find the esys modules
pythonpath_prefix = local['prefix']
if 'PYTHONPATH' in os.environ:
    pythonpath_prefix += os.pathsep + os.environ['PYTHONPATH']
local['ENV']['PYTHONPATH'] = pythonpath_prefix

# Add LD_LIBRARY_PATH so libraries can be found
lib_esys_path = os.path.join(local['prefix'], 'lib', 'esys')
lib_path = os.path.join(local['prefix'], 'lib')
ldlibpath = lib_esys_path + os.pathsep + lib_path

# Add Trilinos library path if available
trilinos_lib = os.path.join(local['prefix'], 'esys.trilinos', 'lib')
if os.path.exists(trilinos_lib):
    ldlibpath += os.pathsep + trilinos_lib

# Add HDF5 library paths (needed for symbol resolution)
# Check common HDF5 locations
hdf5_paths = [
    '/usr/lib/x86_64-linux-gnu/hdf5/serial',  # Debian/Ubuntu
    '/usr/lib64',  # Fedora/RedHat
    '/usr/local/lib',  # From source
]
for hdf5_path in hdf5_paths:
    if os.path.exists(hdf5_path):
        ldlibpath += os.pathsep + hdf5_path

# Add existing LD_LIBRARY_PATH if present
if 'LD_LIBRARY_PATH' in os.environ:
    ldlibpath += os.pathsep + os.environ['LD_LIBRARY_PATH']

local['ENV']['LD_LIBRARY_PATH'] = ldlibpath

#env.Alias(os.path.join(int_dir,'index.rst'),[env['pyinstall'], int_dir],'doc/sphinx_api/genrst.py ./esys esys '+int_dir)

mjpath=''
if env['mathjax_path']!='default':
    mjpath='-D mathjax_path='+env['mathjax_path']

# Build the library path explicitly
lib_paths = [
    os.path.join(local['prefix'], 'lib', 'esys'),
    os.path.join(local['prefix'], 'lib'),
]
if os.path.exists(trilinos_lib):
    lib_paths.append(trilinos_lib)
# Add HDF5 library paths - check both common locations
lib_paths.extend([
    '/lib/x86_64-linux-gnu',              # Where ldconfig finds HDF5 libraries
    '/usr/lib/x86_64-linux-gnu',          # Standard library location
    '/usr/lib/x86_64-linux-gnu/hdf5/serial',  # HDF5 serial build location
])
ldlib_str = ':'.join(lib_paths)

# Create command with explicit environment variable settings
sphinxstuff=local.Command('stuff', [epy_dir, int_dir, env['pyinstall']],
    'export PYTHONPATH='+local['prefix']+':$$PYTHONPATH && ' +
    'export LD_LIBRARY_PATH='+ldlib_str+':$$LD_LIBRARY_PATH && ' +
    'echo "=== Environment Check ===" && ' +
    'echo "PYTHONPATH=$$PYTHONPATH" && ' +
    'echo "LD_LIBRARY_PATH=$$LD_LIBRARY_PATH" && ' +
    'echo "Testing esys module import..." && ' +
    env['pythoncmd'] + ' -c "import sys; import esys.escript; print(\'SUCCESS: esys.escript imported from:\', esys.escript.__file__)" && ' +
    'echo "=== Generating Sphinx RST files from Python modules ===" && ' +
    env['pythoncmd'] + ' doc/sphinx_api/genrst.py '+env['prefix']+' esys '+int_dir+
    ' && echo "=== Copying static RST files to build directory ===" && ' +
    'cp doc/sphinx_api/index.rst '+int_dir+'/ && ' +
    'echo "=== Converting README.md to welcome.rst (requires pandoc) ===" && ' +
    '(pandoc -f markdown -t rst README.md -o '+int_dir+'/welcome.rst || ' +
    '(echo "WARNING: pandoc not found, using pre-built welcome.rst" && ' +
    'cp doc/sphinx_api/welcome.rst '+int_dir+'/)) && ' +
    'echo "=== Converting installation.md to RST (requires pandoc) ===" && ' +
    '(pandoc -f markdown -t rst installation.md -o '+int_dir+'/installation.rst || ' +
    '(echo "WARNING: pandoc not found, using pre-built installation.rst" && ' +
    'cp doc/sphinx_api/installation.rst '+int_dir+'/)) && ' +
    'echo "=== Converting options.md to RST (requires pandoc) ===" && ' +
    '(pandoc -f markdown -t rst scons/templates/options.md -o '+int_dir+'/options.rst || ' +
    '(echo "WARNING: pandoc not found, using pre-built options.rst" && ' +
    'cp doc/sphinx_api/options.rst '+int_dir+'/)) && ' +
    'cp doc/sphinx_api/resources.rst '+int_dir+'/ && ' +
    'cp doc/sphinx_api/mpi4py.rst '+int_dir+'/ && ' +
    'echo "=== Building Sphinx HTML documentation ===" && ' +
    'sphinx-build -v -E --color -b html -d '+int_dir+'/tree -c doc/sphinx_api '+mjpath+' '+int_dir+' '+epy_dir +
    ' && echo "=== Verifying genindex.html ===" && ' +
    'wc -l '+epy_dir+'/genindex.html && ' +
    'grep -c "href=" '+epy_dir+'/genindex.html || echo "genindex.html has no links!"')

# Create dependency on example archives (user PDF may not be built if LaTeX unavailable)
# These files are created by other build steps, we just ensure Sphinx build waits for them
examples_zip_file = os.path.join(release_dir, 'escript_examples.zip')
examples_tar_file = os.path.join(release_dir, 'escript_examples.tar.gz')

# Ensure Sphinx build depends on these resources being available
Depends(sphinxstuff, [examples_zip_file, examples_tar_file])

env.Alias('sphinxdoc', sphinxstuff)
#env.Alias('sphinxdoc', [epy_dir, int_dir], 'doc/sphinx_api/genrst.py '+env['prefix']+' esys '+int_dir+" && sphinx-build -b html -d "+int_dir+"/tree -c doc/sphinx_api "+int_dir+" "+epy_dir)

# This will need to be here at least until the output of api_epydoc properly
# depends on the libraries it uses as input
env.AlwaysBuild('sphinxdoc')

