# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.

import os
import sys
sys.path.insert(0, os.path.abspath('../..'))

import sphinx_gallery.sorting
from MoleCool import __version__

# -- Project information -----------------------------------------------------

project = 'MoleCool'
copyright = '2025, Felix Kogel'
author = 'Felix Kogel'

release = __version__
version = ".".join(release.split(".")[:2])  # major.minor

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    # always put sphinx-gallery first since autosummary or napoleon
    # can alter the python environment slighlty
    'sphinx_gallery.gen_gallery',
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.napoleon',
    
    'sphinx_exec_code',
    'sphinx.ext.viewcode',
    'sphinx.ext.intersphinx',
    # 'sphinx_codeautolink',
    # 'myst_nb',
    "sphinx_copybutton",
    'sphinx_design',
    ]

# manual order of example files as shown in the sphinx-gallery
manual_order = [
    "plot_RabiOsci_2level.py",
    "plot_EIT.py",
    "optcycl_3+1levels.py",
    "optcycl_12+4levels.py",
    "YbOH.py",
    "chirp_slowing.py",
    "plot_spectra_RaF.py",
    "cooling_forces_RaF.py",
    "cooling_forces.py",
    "BCF.py",
    "*",
    ]


sphinx_gallery_conf = {
    "examples_dirs": [
        "../../MoleCool/Examples/core",
        "../../MoleCool/Examples/misc",
        ],        # where your .py tutorials live
    "gallery_dirs": [
        "auto_examples/core",
        "auto_examples/misc",
        ],    # where the generated HTML goes
    'within_subsection_order': sphinx_gallery.sorting.ExplicitOrder(manual_order),
    "remove_config_comments": True,
    # "filename_pattern": r"^((?!advanced).)*$",  # execute everything except examples_static
    
    # Generate backreferences for documented functions/classes
    "doc_module": ("MoleCool",),  # replace with your package’s top-level module
    "backreferences_dir": "gen_modules/backreferences",
    "reference_url": {
        "MoleCool": None,            # resolves to local API docs
    },
    # "download_all_examples": False,   # disables .zip with .ipynb
    # "filename_pattern": r".*",        # process all .py
    # "pypandoc": False,
}

autosummary_generate = True

autosummary_generate_overwrite = False  # prevents accidental clobbering

autodoc_default_options = {
    'members': True,           # include methods/attributes
    'undoc-members': True,     # include even undocumented members
    'inherited-members': True, # show inherited stuff too (optional)
    'show-inheritance': True,  # class hierarchy info
    # 'special-members': '',
}
autodoc_typehints = "description"
autoclass_content = "class" # 'class', 'both', 'init'

# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = False

# Optional: link to external projects (e.g. Python, NumPy, Matplotlib)
intersphinx_mapping = {
    "python": ("https://docs.python.org/3", None),
    "numpy": ('http://docs.scipy.org/doc/numpy', None),
    "scipy": ('http://docs.scipy.org/doc/scipy/reference', None),
    "matplotlib": ("https://matplotlib.org/stable", None),
    'MoleCool': ('../../', 'build/objects.inv'),  # local API inventory
}


# exclude_patterns = [
#     "auto_examples/**/*.ipynb",  # ignore notebooks generated by sphinx-gallery
# ]
# nb_execution_mode = "auto"   # run if outputs missing

# Add all modules that you use in your code and are not part of the standard
# python installation to the autodoc_mock_imports
# This prevents the import of those modules by Sphinx and thereby reduces
# the overhead and makes sure that the documentation can be generated on 
# machines where those modules are not present. 
autodoc_mock_imports=['numpy','matplotlib','scipy','sympy','numba','pandas','tqdm','h5py']

autoclass_content = "both"

# This value selects if automatically documented members are sorted alphabetical
# (value 'alphabetical'), by member type (value 'groupwise') or by source order
# (value 'bysource'). The default is alphabetical.
autodoc_member_order = "bysource"

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# Path for logo/picture relative to docs/source/
html_logo = "_static/molecool_logo.png"
# html_theme_options = {
#     "logo": {
#         "image_light": "_static/MoleCool_picture03_2.png",
#         "image_dark": "_static/MoleCool_picture03_2.png",
        
#         "text": "MoleCool",
#         # "logo_only": True, # for sphinx_rtd_theme
        
#         # Move the logo into the sidebar
#         "navbar_start": ["sidebar-logo"],  # ensure logo is sidebar-anchored
#         "sidebar_end": ["sidebar-logo"],   # alternative: stick at bottom
#     }
# }

html_theme_options = {
    "repository_url": "https://github.com/LangenGroup/MoleCool",
    "use_repository_button": True,
    }
html_title = f"MoleCool v{release} documentation"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_book_theme" #'pydata_sphinx_theme'##'sphinx_rtd_theme' # 'sphinxdoc' 'alabaster'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_css_files = [
    "custom.css",
]



# def append_line_to_gallery_rst(app, env):
#     """
#     Append a note to all .rst files generated by Sphinx-Gallery.
#     """
#     gallery_dir = os.path.join(app.srcdir, 'auto_examples/all')  # adjust folder
#     # line_to_append = "\n.. note:: This line is automatically appended.\n"
#     line_to_append = ("\n.. rst-class:: sphx-glr-timing\n\n   **Total running time of the script:** (0 minutes 0.266 seconds)")
        
#     for root, _, files in os.walk(gallery_dir):
#         for fname in files:
#             if fname.endswith(".rst"):
#                 print('##################################################################')
#                 print('appending line here',fname)
#                 print('##################################################################')            
#                 path = os.path.join(root, fname)
#                 with open(path, "a", encoding="utf-8") as f:
#                     # Avoid duplicate lines
#                     with open(path, "r", encoding="utf-8") as fr:
#                         if line_to_append.strip() in fr.read():
#                             continue
#                     f.write(line_to_append)

# def setup(app):
#     # Run after Sphinx has read all source files (including generated .rst)
#     app.connect('env-updated', append_line_to_gallery_rst)