#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- 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(".."))

DOC_DIR = os.path.abspath(os.path.dirname(__file__))
"""This directory"""


def find_version(*file_paths) -> str:
    """Tries to extract a version from the given path sequence"""
    import codecs
    import os
    import re

    def read(*parts):
        """Reads a file from the given path sequence, relative to this file"""
        here = DOC_DIR
        with codecs.open(os.path.join(here, *parts), "r") as fp:
            return fp.read()

    # Read the file and match the __version__ string
    file = read(*file_paths)
    match = re.search(r"^__version__\s?=\s?['\"]([^'\"]*)['\"]", file, re.M)
    if match:
        return match.group(1)
    raise RuntimeError(f"Unable to find version string in {file_paths}")


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

project = "yayaml"
copyright = "2017 - 2026, Yunus Sevinchan"
author = "Yunus Sevinchan"

# The short X.Y version
version = find_version("..", "yayaml", "__init__.py")

# The full version, including alpha/beta/rc tags
release = find_version("..", "yayaml", "__init__.py")


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

# If your documentation needs a minimal Sphinx version, state it here.
#
needs_sphinx = "5.3"

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.autodoc.typehints",
    "sphinx.ext.intersphinx",
    "sphinx.ext.todo",
    "sphinx.ext.doctest",
    "sphinx.ext.coverage",
    "sphinx.ext.mathjax",
    "sphinx.ext.ifconfig",
    "sphinx.ext.viewcode",
    ### Additional extensions...
    #   ... to allow toggling content
    "sphinx_togglebutton",
    #   ... to pre-process Google-style Python docstrings
    "sphinx.ext.napoleon",
    #   ... to have the IPython directive available for code examples
    "IPython.sphinxext.ipython_console_highlighting",
    "IPython.sphinxext.ipython_directive",
    #   ... to parse Markdown files
    "myst_parser",
]

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

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = {".rst": "restructuredtext", ".md": "markdown"}

# The master toctree document.
master_doc = "index"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"

# 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 = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = None

# Whether module names are prepended to all object names (for object types
# where a “module” of some kind is defined). Default: True
add_module_names = False

# Suppress the module name of the python reference if it can be resolved
python_use_unqualified_type_names = True


# -- Configure autodoc --------------------------------------------------------

autodoc_default_options = {
    "members": True,
    "member-order": "bysource",
    "undoc-members": True,
    "private-members": True,
    "inherited-members": True,
}


# -- 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"

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
# NOTE The issues and edit-page buttons are not working with GitLab repos yet
html_theme_options = {
    "repository_url": "https://gitlab.com/blsqr/yayaml",
    "use_repository_button": True,
    "use_issues_button": False,
    "use_edit_page_button": False,
    "use_download_button": True,
    "use_fullscreen_button": False,
}


# 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"]

# Custom CSS files, assumed relative to `html_static_path` or full URI
html_css_files = ["css/custom.css"]

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself.  Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}


# Title, Logo, Favicon
#
html_title = ""
html_logo = ""  # "_static/img/logo.svg"
html_favicon = ""  # "_static/img/icon.png"


# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "yayaml-doc"


# -- Options for LaTeX output ------------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',
    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (
        master_doc,
        "YAYAML.tex",
        "YAYAML Documentation",
        author,
        "manual",
    ),
]


# -- Options for manual page output ------------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (
        master_doc,
        "YAYAML",
        "YAYAML Documentation",
        [author],
        1,
    )
]


# -- Options for Texinfo output ----------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        master_doc,
        "YAYAML",
        "YAYAML Documentation",
        author,
        "YAYAML",
        "",
        "Research Software",
    ),
]


# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ["search.html"]


# -- Extension configuration -------------------------------------------------

# -- Options for todo extension ----------------------------------------------

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True


# -- Napoleon configuration --------------------------------------------------

napoleon_google_docstring = True
# Whether to parse Google style docstrings. (default: true)

napoleon_numpy_docstring = False
# Whether to parse numpy style docstrings. (default: true)

napoleon_include_init_with_doc = True
# True to list __init___ docstrings separately from the class docstring.
# False to fall back to Sphinx’s default behavior, which considers the
# __init___ docstring as part of the class documentation. Defaults to False.

napoleon_include_private_with_doc = False
# True to include private members (like _membername) with docstrings in the
# documentation. False for Sphinx’s default behavior. Default: False

napoleon_include_special_with_doc = True
# True to include special members (like __membername__) with docstrings in the
# documentation. False to fall back to Sphinx’s default behavior. Default: True


# -- IPython Configuration ----------------------------------------------------
# See https://ipython.readthedocs.io/en/stable/sphinxext.html

# NOTE Using default values.


# -- Intersphinx --------------------------------------------------------------

# Mappings can be looked up from the following GitHub gist:
#   https://gist.github.com/bskinn/0e164963428d4b51017cebdb6cda5209
#
# Further documentation:
#   https://docs.readthedocs.io/en/stable/guides/intersphinx.html
#   https://www.sphinx-doc.org/en/master/usage/extensions/intersphinx.html
#
# In case reference targeting fails, consider using the sphobjinv package
#   https://github.com/bskinn/sphobjinv

# fmt: off
intersphinx_mapping = {
    #
    # First-party docs:
    # ...
    #
    # Third-party docs
    "python":       ("https://docs.python.org/3/", None),
    "sphinx":       ("https://www.sphinx-doc.org/en/master/", None),
    "h5py":         ("https://docs.h5py.org/en/latest/", None),
    "matplotlib":   ("https://matplotlib.org/stable/", None),
    "seaborn":      ("https://seaborn.pydata.org", None),
    "numpy":        ("https://numpy.org/doc/stable/", None),
    "pandas":       ("https://pandas.pydata.org/docs/", None),
    "scipy":        ("https://docs.scipy.org/doc/scipy/", None),
    "xarray":       ("https://docs.xarray.dev/en/stable/", None),
    "dask":         ("https://docs.dask.org/en/stable/", None),
    "networkx":     ("https://networkx.org/documentation/stable/", None),
    "sympy":        ("https://docs.sympy.org/latest/", None),
    "dill":         ("https://dill.readthedocs.io/en/latest/", None),
    "pytest":       ("https://pytest.org/en/stable/", None),
}
# fmt: on


# -- Nitpicky Configuration ---------------------------------------------------

# Be nitpicky about warnings, to show all references where the target could
# not be found
nitpicky = True
nitpick_ignore = []
nitpick_ignore_regex = []

# ... however, we need to exclude quite a lot, so we load the to-be-ignored
# references from a file. This is a list of (type, target) tuples, both entries
# being strings, e.g. `('py:func', 'int')`.
#
# The individual entries can also be regex patterns. To add an entry to the
# regex list instead of the non-regex list, prefix a line with "re: ", e.g.:
#
#       re: py:func ^int$
#
# See the following page for more information and syntax:
#  www.sphinx-doc.org/en/master/usage/configuration.html#confval-nitpick_ignore

for line in open(".nitpick-ignore"):
    line = line.strip()
    if not line or line.startswith("#"):
        continue

    if line.startswith("re: "):
        _, reftype, target = line.split(" ", 2)
        nitpick_ignore_regex.append((reftype, target.strip()))

    else:
        reftype, target = line.split(" ", 1)
        nitpick_ignore.append((reftype, target.strip()))


# -----------------------------------------------------------------------------
# -- Functions used in sphinx setup function ----------------------------------
# -----------------------------------------------------------------------------


def run_apidoc(_):
    """A function to run apidoc, creating the API documentation"""
    ignore_paths = []

    # Get the required directory paths
    cur_dir = os.path.abspath(os.path.dirname(__file__))
    out_dir = os.path.join(cur_dir, "api")
    module = os.path.join(cur_dir, "..", "yayaml")

    argv = [
        "--force",
        # "--separate",
        "--private",
        "--module-first",
        "--no-toc",
        "-o",
        out_dir,
        module,
    ] + ignore_paths

    from sphinx.ext import apidoc

    apidoc.main(argv)


# .. Figure generation ........................................................


def _str2bool(val: str):
    """Copy of strtobool from deprecated distutils package"""
    val = val.lower()
    if val in ("y", "yes", "t", "true", "on", "1"):
        return True
    elif val in ("n", "no", "f", "false", "off", "0"):
        return False
    raise ValueError(f"Invalid truth value {repr(val)}!")


def generate_figures():
    """Generates output from scripts in a certain module"""
    _ENV_PREFIX = "YAYAML"

    # Check environment variable
    TOGGLE_ENVVAR = f"{_ENV_PREFIX}_DOC_GENERATE_FIGURES"
    print(
        f"Checking {TOGGLE_ENVVAR} environment variable for "
        "whether figures should be generated ..."
    )
    if not os.environ.get(TOGGLE_ENVVAR) or not _str2bool(
        os.environ.get(TOGGLE_ENVVAR, "False")
    ):
        print(
            f"Not generating figures. Set the {TOGGLE_ENVVAR} "
            "environment variable to control this behavior.\n\n"
        )
        return

    # Generate paths
    gen_fig_dir = os.path.join(DOC_DIR, "..", "tests", "_gen_figures")
    out_dir = os.path.join(DOC_DIR, "_static", "_gen")

    # Set environment variables such that test output ends up in the desired
    # output directory. The abbreviated path means that not the full module
    # string of the test module is included into the path but only the name of
    # the test function (with the `test_` prefix dropped).
    os.environ[f"{_ENV_PREFIX}_USE_TEST_OUTPUT_DIR"] = "yes"
    os.environ[f"{_ENV_PREFIX}_TEST_OUTPUT_DIR"] = str(out_dir)
    os.environ[f"{_ENV_PREFIX}_ABBREVIATE_TEST_OUTPUT_DIR"] = "yes"
    os.environ[f"{_ENV_PREFIX}_TEST_VERBOSITY"] = "1"  # not overly verbose

    # Let pytest do the rest
    print("Now invoking (pytest-based) figure generation module ...\n")

    import pytest

    rv = pytest.main(["-v", gen_fig_dir])
    if rv != 0:
        raise RuntimeError(
            "Figure generation failed! See error log above for more info."
        )
    print("\nFigure generation finished successfully. Yay :)\n")

    # Give some stats
    num_files = 0
    all_files = []
    for dirpath, dirnames, filenames in os.walk(out_dir):
        rel_dir = os.path.relpath(dirpath, out_dir)
        files = [
            os.path.join(rel_dir, f)
            for f in filenames
            if not f.startswith(".")
        ]
        num_files += len(files)
        all_files += files

    _files = "\n".join(f"  {f}" for f in all_files)
    print(
        f"Output directory\n  {out_dir}\ncontains {num_files} files:\n"
        f"{_files}\n\n"
    )


def setup(app):
    """A custom sphinx setup function, invoking run_apidoc"""
    generate_figures()

    app.connect("builder-inited", run_apidoc)
