# -*- coding: utf-8 -*-
#
# ddtrace documentation build configuration file, created by
# sphinx-quickstart on Thu Jul  7 17:25:05 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# 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.
#
from datetime import datetime
import glob
import os
import os.path
import re
import sys
from typing import Any  # noqa
from typing import Optional  # noqa

from docutils import nodes
from docutils import statemachine
from docutils.parsers import rst
from enchant.tokenize import Filter
from sphinx.util import logging
import yaml


# from setuptools-scm
# https://github.com/pypa/setuptools_scm/blob/69b88a20c5cd4632ef0c97b3ddd2bd0d3f8f7df8/src/setuptools_scm/config.py#L9
VERSION_TAG_REGEX_STRING = r"^(?:[\w-]+-)?(?P<version>[vV]?\d+(?:\.\d+){0,2}[^\+]*)(?:\+.*)?$"
VERSION_TAG_REGEX = re.compile(VERSION_TAG_REGEX_STRING)


class VersionTagFilter(Filter):
    """If a word matches a version tag used for the repository"""

    def _skip(self, word):
        return VERSION_TAG_REGEX.match(word)


# append the ddtrace path to syspath
# this is required when building the docs manually
if not os.getenv("READTHEDOCS") == "True":
    sys.path.insert(0, os.path.abspath(".."))


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

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

# 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.extlinks",
    "sphinx.ext.intersphinx",
    "sphinxcontrib.spelling",
    "sphinx_copybutton",  # https://sphinx-copybutton.readthedocs.io/
]

# Add filters for sphinxcontrib.spelling
spelling_filters = [VersionTagFilter]

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

# Enable links to the python standard doc.
intersphinx_mapping = {
    "python": ("https://docs.python.org/3", None),
}

# The encoding of source files.
#
# source_encoding = 'utf-8-sig'

# The master toctree document.
master_doc = "index"

# General information about the project.
year = datetime.now().year
project = "ddtrace"
copyright = "2016-{}, Datadog, Inc.".format(year)  # noqa: A001
author = "Datadog, Inc."

# document in order of source
autodoc_member_order = "bysource"


# 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.
# version = u'0.2'
# The full version, including alpha/beta/rc tags.
# release = u'0.2'

# 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 = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'

# Patterns, relative to the source directory, for files and directories to ignore when searching for source files.
exclude_patterns = [
    # These patterns also affect html_static_path and html_extra_path.
    "_build",
    "Thumbs.db",
    ".DS_Store",
    "**/__pycache__/*",
]

# autodoc_mock_imports contains a list of modules to be mocked up.
# Excludes files that require third-party packages not included with ddtrace,
# preventing Sphinx build failures due to module not found errors. Allows __init__.py files to be included
# since these are often used to define integration-level docstrings.
autodoc_mock_imports = [
    path.replace(os.path.sep, ".")[:-3].strip(".")
    for path in glob.glob("../ddtrace/contrib/internal/**/*.py", recursive=True)
    if not path.endswith("__init__.py")
]

# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None

# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True

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

# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False

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

# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []

# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False

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


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

# 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.
#
# See https://pradyunsg.me/furo/customisation/
DATADOG_DARK_PURPLE = "#632CA6"

html_theme_options = {
    "light_css_variables": {
        "color-brand-primary": DATADOG_DARK_PURPLE,
        "color-brand-content": DATADOG_DARK_PURPLE,
    },
    "dark_css_variables": {
        # TODO: update to use a correct color, since dark purple is hard to read
        # "color-brand-primary": DATADOG_DARK_PURPLE,
        # "color-brand-content": DATADOG_DARK_PURPLE,
    },
}

# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []

# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
html_title = "ddtrace python documentation"

# A shorter title for the navigation bar.  Default is the same as html_title.
#
# html_short_title = None

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None

# The name of an image file (relative to this directory) to use as a favicon of
# the docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
html_favicon = "favicon.ico"

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

# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []

# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True

# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {"**": [""]}

# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}

# If false, no module index is generated.
#
# html_domain_indices = True

# If false, no index is generated.
#
# html_use_index = True

# If true, the index is split into individual pages for each letter.
#
# html_split_index = False

# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True

# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True

# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True

# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it.  The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''

# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None

# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
#   'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
#   'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'

# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}

# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'

# Output file base name for HTML help builder.
htmlhelp_basename = "ddtracedoc"

# -- 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',
}  # type: dict[str, str]

# 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, "ddtrace.tex", html_title, "Datadog, Inc", "manual"),
]

# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None

# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False

# If true, show page references after internal links.
#
# latex_show_pagerefs = False

# If true, show URL addresses after external links.
#
# latex_show_urls = False

# Documents to append as an appendix to all manuals.
#
# latex_appendices = []

# If false, no module index is generated.
#
# latex_domain_indices = True


# -- 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, "ddtrace", html_title, [author], 1)]

# If true, show URL addresses after external links.
#
# man_show_urls = False


# -- 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,
        "ddtrace",
        html_title,
        author,
        "ddtrace",
        "One line description of project.",
        "Miscellaneous",
    ),
]

# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []

# If false, no module index is generated.
#
# texinfo_domain_indices = True

# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'

# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False


LOG = logging.getLogger(__name__)


class DDTraceConfigurationOptionsDirective(rst.Directive):
    r"""
    Directive class to handle ``.. ddtrace-configuration-options::`` directive.

    For example::

        .. ddtrace-configuration-options::
    """

    has_content = True

    def run(self):
        options = yaml.load("\n".join(self.content), Loader=yaml.CLoader)

        results = statemachine.ViewList()
        for var_name, value in options.items():
            skip_label = value.get("skip_label") == "true"
            var_label = var_name.lower().replace("_", "-")
            var_description = value["description"]
            var_type = value.get("type") or "String"
            var_default = value.get("default") or "(no value)"
            var_version_added = value.get("version_added")

            if not skip_label:
                results.append(".. _`{}`:".format(var_label), "", 0)
                results.append("", "", 0)
            results.append(".. py:data:: {}".format(var_name), "", 0)
            results.append("", "", 0)
            for line in var_description.splitlines():
                results.append("    " + line.lstrip(), "", 0)

            results.append("", "", 0)
            results.append("    **Type**: {}".format(var_type), "", 0)
            results.append("", "", 0)
            results.append("    **Default**: {}".format(var_default), "", 0)
            results.append("", "", 0)

            if var_version_added:
                for version, note in var_version_added.items():
                    if note:
                        results.append(
                            "    *Changed in version {}*: {}".format(version, note),
                            "",
                            0,
                        )
                    else:
                        results.append("    *New in version {}.*".format(version), "", 0)
                    results.append("", "", 0)

        # Generate the RST nodes to return for rendering
        node = nodes.section()
        node.document = self.state.document
        self.state.nested_parse(results, 0, node)
        return node.children


def asbool(argument):
    return argument.lower() in {"yes", "true", "t", "1", "y", "on"}


class DDEnvierConfigurationDirective(rst.Directive):
    required_arguments = 1
    optional_arguments = 0
    final_argument_whitespace = True
    option_spec = {
        "recursive": asbool,
    }

    def run(self):
        module_name, _, config_class = self.arguments[0].partition(":")
        __import__(module_name)
        module = sys.modules[module_name]

        config_spec = None
        for part in config_class.split("."):
            config_spec = getattr(module, part)
        if config_spec is None:
            raise ValueError("Could not find configuration spec class {} from {}".format(config_class, module_name))

        recursive = self.options.get("recursive", False)

        results = statemachine.ViewList()

        for var_name, var_type, var_default, var_description in config_spec.help_info(recursive=recursive):
            var_name = var_name.replace("``", "")

            var_label = var_name.lower().replace("_", "-")

            results.append(".. _`{}`:".format(var_label), "", 0)
            results.append("", "", 0)

            results.append(".. py:data:: {}".format(var_name), "", 0)
            results.append("", "", 0)
            for line in var_description.splitlines():
                results.append("    " + line.lstrip(), "", 0)

            results.append("", "", 0)
            results.append("    **Type**: {}".format(var_type), "", 0)
            results.append("", "", 0)
            results.append("    **Default**: {}".format(var_default), "", 0)
            results.append("", "", 0)

        # Generate the RST nodes to return for rendering
        node = nodes.section()
        node.document = self.state.document
        self.state.nested_parse(results, 0, node)
        return node.children


def setup(app):
    app.add_directive("ddtrace-configuration-options", DDTraceConfigurationOptionsDirective)
    app.add_directive("ddtrace-envier-configuration", DDEnvierConfigurationDirective)
    metadata_dict = {"version": "1.0.0", "parallel_read_safe": True}
    return metadata_dict
