from __future__ import annotations

from urllib.request import urlopen


# Code from https://raw.githubusercontent.com/inducer/sphinxconfig/main/sphinxconfig.py
from os.path import dirname as _dirname, basename as _basename

html_theme = "furo"
html_show_sourcelink = True

# Hardcode project name, closing #996834
project = "pytools"

autoclass_content = "class"

copybutton_prompt_text = r">>> |\.\.\. |\$ |In \[\d*\]: | {2,5}\.\.\.: | {5,8}: "
copybutton_prompt_is_regexp = True


def linkcode_resolve(domain, info, linkcode_url=None):
    import os
    import sys
    import inspect

    if domain != "py" or not info["module"]:
        return None

    submodname = info["module"]
    topmodname = submodname.split(".")[0]
    fullname = info["fullname"]

    topmod = sys.modules.get(topmodname)
    submod = sys.modules.get(submodname)
    if submod is None:
        return None

    obj = submod
    for part in fullname.split("."):
        try:
            obj = getattr(obj, part)
        except Exception:
            return None

    try:
        modpath = os.path.dirname(os.path.dirname(inspect.getsourcefile(topmod)))
        filepath = os.path.relpath(inspect.getsourcefile(obj), modpath)
        if filepath is None:
            return
    except Exception:
        return None

    try:
        source, lineno = inspect.getsourcelines(obj)
    except OSError:
        return None
    else:
        linestart, linestop = lineno, lineno + len(source) - 1

    if linkcode_url is None:
        linkcode_url = (
            f"https://github.com/inducer/{project}/blob/"
            + "main"
            + "/{filepath}#L{linestart}-L{linestop}"
        )

    return linkcode_url.format(
        filepath=filepath, linestart=linestart, linestop=linestop
    )


extensions = [
        "sphinx.ext.autodoc",
        "sphinx.ext.intersphinx",
        "sphinx.ext.linkcode",
        "sphinx.ext.doctest",
        "sphinx.ext.mathjax",
        "sphinx_copybutton",
        ]

__all__ = ("html_theme", "html_show_sourcelink",
        "project", "autoclass_content",
        "copybutton_prompt_text",
        "copybutton_prompt_is_regexp",
        "linkcode_resolve",
        "extensions")

copyright = "2009-21, Andreas Kloeckner"
author = "Andreas Kloeckner"

# 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.
#
# The short X.Y version.
ver_dic = {}
with open("../pytools/version.py") as vfile:
    exec(compile(vfile.read(), "../pytools/version.py", "exec"),
        ver_dic)

version = ".".join(str(x) for x in ver_dic["VERSION"])
release = ver_dic["VERSION_TEXT"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

intersphinx_mapping = {
    "loopy": ("https://documen.tician.de/loopy", None),
    "numpy": ("file:///usr/share/doc/python-numpy-doc/html/",
        "/usr/share/doc/python-numpy/html/objects.inv"),
    "pymbolic": ("https://documen.tician.de/pymbolic", None),
    "pytest": ("file:///usr/share/doc/python-pytest-doc/html/",
        "/usr/share/doc/python-pytest-doc/html/objects.inv"),
    "setuptools": ("https://setuptools.pypa.io/en/latest", None),
    "python": ("file:///usr/share/doc/python3-doc/html/",
        "/usr/share/doc/python3-doc/html/objects.inv"),
    "platformdirs": ("https://platformdirs.readthedocs.io/en/latest", None),
}

nitpicky = True
nitpick_ignore_regex = [
    ["py:class", r"typing_extensions\.(.+)"],
    ["py:class", r"ReadableBuffer"],
]

autodoc_type_aliases = {
    "GraphT": "pytools.graph.GraphT",
    "NodeT": "pytools.graph.NodeT",
}
