# automatically generated by auxilium
# pylint: disable=invalid-name, redefined-builtin
import importlib
import os
import re
import sys
import typing as tp
from importlib import metadata
from pathlib import Path

import requests

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

root = Path(__file__).resolve().parent
project_root = root.parent.parent

project = "{{ aux.project.name }}"
project_dir = project_root / "{{ aux.project.source_dir }}/{{ aux.project.namespace_name }}"
project_doc = project_root / "{{ aux.docs.root }}"

sys.path.append(str(project_dir))
copyright = "{{ aux.project.active_years }}, {{ aux.project.author }}"
author = "{{ aux.project.author }}"


def get_version():
    mod = importlib.import_module(project)
    return mod.__version__


# The full version, including alpha/beta/rc tags
release = get_version()

# -- General configuration ---------------------------------------------------
nitpicky = True

# 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.napoleon",
    "sphinx.ext.linkcode",
    "sphinx.ext.viewcode",
    "sphinx.ext.mathjax",
    "sphinx.ext.intersphinx",
    "sphinx_click",
    "jupyter_sphinx",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = [str(root / "templates")]

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


# -- Options for HTML output -------------------------------------------------
html_theme = "sphinx_rtd_theme"
html_css_files = ["git-link-color.css"]

# 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 = [str(root / "static")]
if (project_doc / "templates").exists():
    html_static_path.append(str(project_doc / "templates"))

if (project_doc / "static").exists():
    html_static_path.append(str(project_doc / "static"))


# -- Options for Plugins -----------------------------------------------------
# linkcode specific funcion
def linkcode_resolve(suffix: str, info: tp.Dict[str, str]) -> tp.Optional[str]:
    if suffix != "py":
        return None
    if not info["module"]:
        return None
    filename = info["module"].replace(".", "/")
    mod = importlib.import_module(filename)

    try:
        x = getattr(mod, info["fullname"])
    except AttributeError:
        return None
    file_ = x.__module__.replace(".", "/")
    git_remote = "{{ aux.project.project_urls.Source }}"
    {% if aux.project.namespace_name -%}
    file_ = f"{{aux.project.namespace_name}}/{file_}"
    {%- endif -%}
    return f"{git_remote}/-/blob/develop/{{ aux.project.source_dir }}/{file_}.{suffix}"


intersphinx_mapping = {"python": ("https://docs.python.org/{{ aux.project.minimal_version }}", None)}
GITLAB_URL_PATTERN = re.compile(r"https:\/\/([\w]+).pages.([^\/]+)\/([\w]+)")


def download_from_artefact(
    doc_url: str, branch: str = "release"
) -> tp.Tuple[str, tp.Optional[str]]:
    # check if objects.inv is publically accessible
    resp = requests.get(f"{doc_url}/objects.inv")
    if "Sign in" not in resp.content.decode("utf8"):
        return doc_url, None

    match = GITLAB_URL_PATTERN.match(doc_url)
    assert match
    user = match.group(1)
    domain = match.group(2)
    repo = match.group(3)
    filename = f"objects-{repo}.inv"

    auth = os.environ["CI_JOB_TOKEN"]

    # auth: headers for local and params for CI
    headers = {}
    headers["PRIVATE-TOKEN"] = auth
    url = f"https://gitlab.{domain}/api/v4/projects/{user}%2F{repo}/jobs/artifacts/{branch}/raw/public/objects.inv"
    req = requests.get(url, headers=headers, params=dict(job="pages", job_token=auth))

    try:
        text = req.content.decode("utf8")
        raise RuntimeError(text)
    except UnicodeDecodeError:
        with open(filename, "wb") as f:
            f.write(req.content)

    return (doc_url, filename)


def from_meta(package_name: str) -> tp.Tuple[str, tp.Optional[str]]:
    meta = metadata.metadata(package_name)

    for key, val in meta.items():
        if key != "Project-URL":
            continue
        if val.startswith("Documentation"):
            url = val.split(",", 1)[1].strip()
            # follow url for redirects (language/version/...)
            req = requests.get(url)
            return req.url, None
    raise RuntimeError(
        f"cannot extract Documentation url from metadata for {package_name}"
    )
