# Configuration file for the Sphinx documentation builder.

import datetime
import os

# Get configuration information from setup.cfg
from configparser import ConfigParser

import magicctapipe

setup_cfg = ConfigParser()
setup_cfg.read([os.path.join(os.path.dirname(__file__), "..", "setup.cfg")])
setup_metadata = dict(setup_cfg.items("metadata"))
setup_options = dict(setup_cfg.items("options"))

# -- General configuration

extensions = [
    "sphinx.ext.duration",
    "sphinx.ext.doctest",
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.intersphinx",
    "sphinx.ext.todo",
    "sphinx.ext.coverage",
    "sphinx.ext.viewcode",
    "sphinx.ext.githubpages",
    "sphinx.ext.mathjax",
    "sphinx_automodapi.automodapi",
    "sphinx_automodapi.smart_resolver",
    "numpydoc",
    "sphinx_design",
]

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

numpydoc_show_class_members = False
numpydoc_class_members_toctree = False
nbsphinx_timeout = 200  # allow max 2 minutes to build each notebook

# These links are ignored in the checks, necessary due to broken intersphinx for
# these
nitpick_ignore = [
    # needed for building the docs with python 3.11 locally.
    # we use the lowest supported version on readthedocs, so that is what we use the intersphinx
    # link above
    ("py:class", "enum.StrEnum"),
    # these are coming from traitlets:
    ("py:class", "t.Union"),
    ("py:class", "t.Any"),
    ("py:class", "t.Dict"),
    ("py:class", "t.Optional"),
    ("py:class", "t.Type"),
    ("py:class", "t.List"),
    ("py:class", "t.Tuple"),
    ("py:class", "Config"),
    ("py:class", "traitlets.config.configurable.Configurable"),
    ("py:class", "traitlets.traitlets.HasTraits"),
    ("py:class", "traitlets.traitlets.HasDescriptors"),
    ("py:class", "traitlets.traitlets.TraitType"),
    ("py:class", "traitlets.traitlets.BaseDescriptor"),
    ("py:class", "traitlets.traitlets.List"),
    ("py:class", "traitlets.traitlets.Container"),
    ("py:class", "traitlets.traitlets.Instance"),
    ("py:class", "traitlets.traitlets.ClassBasedTraitType"),
    ("py:class", "traitlets.traitlets.Int"),
    ("py:class", "traitlets.config.application.Application"),
    ("py:class", "traitlets.utils.sentinel.Sentinel"),
    ("py:class", "traitlets.traitlets.ObserveHandler"),
    ("py:class", "StrDict"),
    ("py:class", "ClassesType"),
    ("py:obj", "traitlets.traitlets.G"),
    ("py:obj", "traitlets.traitlets.S"),
    ("py:class", "traitlets.traitlets.T"),
    ("py:class", "re.Pattern[t.Any]"),
    ("py:class", "Sentinel"),
    ("py:class", "ObserveHandler"),
    ("py:obj", "traitlets.config.boolean_flag"),
    ("py:obj", "traitlets.TraitError"),
    ("py:obj", "-v"),  # fix for wrong syntax in a traitlets docstring
    ("py:meth", "MetaHasDescriptors.__init__"),
    ("py:meth", "HasTraits.__new__"),
    ("py:meth", "BaseDescriptor.instance_init"),
    ("py:obj", "cls"),
    ("py:obj", "name"),
    ("py:obj", "Field"),
    ("py:obj", "deg"),
    ("py:obj", "m"),
    ("py:obj", "TeV"),
    ("py:obj", "rad"),
    ("py:obj", "s"),
    ("py:obj", "ns"),
    ("py:class", "astropy.coordinates.baseframe.BaseCoordinateFrame"),
    ("py:class", "astropy.table.table.Table"),
    ("py:class", "eventio.simtel.simtelfile.SimTelFile"),
    ("py:class", "ctapipe.compat.StrEnum"),
    ("py:class", "ctapipe.core.container.Container"),
]

numpydoc_xref_param_type = True
numpydoc_xref_ignore = {"type", "optional", "default"}

# Report warnings for all validation checks except those after all
numpydoc_validation_checks = {
    "all",
    "EX01",
    "ES01",
    "GL01",
    "PR09",
    "RT05",
    "SA01",
    "SS03",
    "SS05",
    "SS06",
}
# don't report on objects that match any of these regex
numpydoc_validation_exclude = {
    "magicctapipe.io.BaseEventInfoContainer",
    "magicctapipe.io.RealEventInfoContainer",
    "magicctapipe.io.SimEventInfoContainer",
}

# -- Project information

project = setup_metadata["name"]
author = setup_metadata["author"]
copyright = "{}.  Last updated {}".format(
    setup_metadata["author"], datetime.datetime.now().strftime("%d %b %Y %H:%M")
)
python_requires = setup_options["python_requires"]

# make some variables available to each page
rst_epilog = f"""
.. |python_requires| replace:: {python_requires}
"""

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.

version = magicctapipe.__version__
# The full version, including alpha/beta/rc tags.
release = version

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

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

# Define the json_url for our version switcher.
json_url = "https://magic-cta-pipe.readthedocs.io/en/latest/_static/switcher.json"

# Define the version we use for matching in the version switcher.,
version_match = os.getenv("READTHEDOCS_VERSION")
# If READTHEDOCS_VERSION doesn't exist, we're not on RTD
# If it is an integer, we're in a PR build and the version isn't correct.
if not version_match or version_match.isdigit():
    # For local development, infer the version to match from the package.
    if "dev" in release or "rc" in release:
        version_match = "latest"
    else:
        version_match = release

    # We want to keep the relative reference when on a pull request or locally
    json_url = "_static/switcher.json"

# -- Options for HTML output
# 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.
html_theme_options = {
    "github_url": "https://github.com/cta-observatory/magic-cta-pipe",
    "header_links_before_dropdown": 6,
    "navbar_start": ["navbar-logo", "version-switcher"],
    "navigation_with_keys": False,
    "switcher": {
        "version_match": version_match,
        "json_url": json_url,
    },
    "use_edit_page_button": True,
    "icon_links_label": "Quick Links",
    "icon_links": [
        {
            "name": "CTA Observatory",
            "url": "https://www.cta-observatory.org/",
            "type": "url",
            "icon": "https://www.cta-observatory.org/wp-content/themes/ctao/favicon.ico",
        },
    ],
    "announcement": """
        <p>magic-cta-pipe is under active development. Expect large and rapid changes in functionality.</p>
    """,
}

# 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_context = {
    "default_mode": "light",
    "github_user": "cta-observatory",
    "github_repo": "magic-cta-pipe",
    "github_version": "master",
    "doc_path": "docs",
}
html_css_files = ["magicctapipe.css"]
html_file_suffix = ".html"

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
html_title = f"{project} v{release}"

# Output file base name for HTML help builder.
htmlhelp_basename = project + "doc"

html_theme = "pydata_sphinx_theme"

intersphinx_mapping = {
    "python": ("https://docs.python.org/3.11", None),
    "numpy": ("https://numpy.org/doc/stable/", None),
    "scipy": ("https://docs.scipy.org/doc/scipy/", None),
    "astropy": ("https://docs.astropy.org/en/stable/", None),
    "pytables": ("http://www.pytables.org/", None),
    "pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None),
    "matplotlib": ("https://matplotlib.org/stable", None),
    "cython": ("https://docs.cython.org/en/latest/", None),
    "iminuit": ("https://scikit-hep.org/iminuit/", None),
    "traitlets": ("https://traitlets.readthedocs.io/en/stable/", None),
    "ctapipe": ("https://ctapipe.readthedocs.io/en/v0.19.2/", None),
    "pyirf": ("https://pyirf.readthedocs.io/en/stable/", None),
}

# -- Options for EPUB output
epub_show_urls = "footnote"
