# -*- coding: utf-8 -*-
#
# 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.
import asyncio
import csv
import inspect
import os
import shutil
import sys

__location__ = os.path.join(os.getcwd(), os.path.dirname(inspect.getfile(inspect.currentframe())))

from itertools import pairwise

# 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 pathlib import Path
from typing import Iterable

from bo4e_cli.diff.diff import diff_schemas
from bo4e_cli.diff.matrix import create_compatibility_matrix, create_graph_from_changes, get_path_through_di_path_graph
from bo4e_cli.edit.update_refs import update_references_all_schemas
from bo4e_cli.io.changes import write_changes
from bo4e_cli.io.git import get_last_n_tags
from bo4e_cli.io.github import download_schemas
from bo4e_cli.io.matrix import write_compatibility_matrix_csv
from bo4e_cli.io.schemas import read_schemas, write_schemas
from bo4e_cli.models.changes import Changes
from bo4e_cli.models.meta import Schemas
from bo4e_cli.models.version import Version
from bo4e_cli.utils.github_cli import get_access_token_from_cli_if_installed

from bo4e import __gh_version__, __version__

sys.path.insert(0, os.path.join(__location__, "../src"))
sys.path.insert(0, os.path.join(__location__, "../docs"))
sys.path.insert(0, os.path.join(__location__, "../docs/compatibility"))
import uml

# import package bo4e to clarify namespaces and prevent circular import errors
from bo4e import *

# -- Run sphinx-apidoc ------------------------------------------------------
# This hack is necessary since RTD does not issue `sphinx-apidoc` before running
# `sphinx-build -b html . _build/html`. See Issue:
# https://github.com/rtfd/readthedocs.org/issues/1139
# DON'T FORGET: Check the box "Install your project inside a virtualenv using
# setup.py install" in the RTD Advanced Settings.
# Additionally, it helps us to avoid running apidoc manually

try:  # for Sphinx >= 1.7
    from sphinx.ext import apidoc
except ImportError:
    from sphinx import apidoc

output_dir = os.path.join(__location__, "api")
module_dir = os.path.join(__location__, "../src/bo4e")
try:
    shutil.rmtree(output_dir)
except FileNotFoundError:
    pass

try:
    import sphinx

    cmd_line_template = "sphinx-apidoc -f -o {outputdir} {moduledir}"
    cmd_line = cmd_line_template.format(outputdir=output_dir, moduledir=module_dir)

    args = cmd_line.split(" ")
    args = args[1:]

    apidoc.main(args)
except Exception as e:
    print("Running `sphinx-apidoc` failed!\n{}".format(e))

# -- 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.intersphinx",
    "sphinx.ext.todo",
    "sphinx.ext.autosummary",
    "sphinx.ext.viewcode",
    "sphinx.ext.coverage",
    "sphinx.ext.doctest",
    "sphinx.ext.ifconfig",
    "sphinx.ext.mathjax",
    "sphinx.ext.napoleon",
    "sphinx_rtd_theme",
]


def skip_pydantic_internals(app, what, name, obj, skip, options):
    """
    This processor is used to filter out Pydantic internal attributes from the
    documentation.
    """
    if name in ("model_fields", "model_config", "model_computed_fields"):
        return True
    return skip


def setup(app):
    app.connect("autodoc-skip-member", skip_pydantic_internals)


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

# The suffix of source filenames.
source_suffix = ".rst"

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

# The master toctree document.
master_doc = "index"

# General information about the project.
project = "bo4e"
copyright = "2022, Hochfrequenz GmbH"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# 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'

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ["_build"]

# 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


# -- 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_rtd_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.
html_theme_options = {
    "logo_only": False,
    "prev_next_buttons_location": "bottom",
    "style_external_links": False,
    # There is still a bug which will probably get fixed soon
    # https://github.com/readthedocs/sphinx_rtd_theme/pull/1010
    # therefore the option vcs_pageview_mode is commented out
    # "vcs_pageview_mode": "blob",
    "style_nav_header_background": "white",
    # Toc options
    "collapse_navigation": True,
    "sticky_navigation": True,
    "navigation_depth": 4,
    "includehidden": True,
    "titles_only": False,
}

html_css_files = [
    "css/override.css",
    "css/colors.css",
]
rst_prolog = """
.. role:: main-color
.. role:: sub-color
.. role:: error-color
"""

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

# The name for this set of Sphinx documents.  If None, it defaults to
# "<project> v<release> documentation".
# Note: For the deployment to GitHub Pages the release and version values will
# be set by the action. This is to support things like /latest or /stable.
if "release" not in globals():
    release = os.getenv("SPHINX_DOCS_RELEASE")
    if not release:
        release = __gh_version__
if "version" not in globals():
    version = os.getenv("SPHINX_DOCS_VERSION")
    if not version:
        version = __version__

print(f"Got version = {version} from __version__")
print(f"Got release = {release} from __gh_version__")

# 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 = "./_static/bo4e-python-logo.png"

# The name of an image file (within the static path) to use as favicon of the
# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = "./_static/bo4e-python-favicon.png"

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

# This flag ignores the `__all__` variable. Without this, the `__all__` variable
# in `bo4e.__init__.py` would disable sphinx-autodoc from resolving the
# ambiguous definitions of the classes. It would lead to the following error:
#
# docstring of bo4e.bo.angebot.Angebot.externe_referenzen:1:
# more than one target found for cross-reference 'ZusatzAttribute':
# bo4e.ZusatzAttribute, bo4e.com.zusatzattribute.ZusatzAttribute
#
# This flag is not well documented.
# https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_default_options
# It is better to take a look at the PR and the corresponding issue directly:
# https://github.com/sphinx-doc/sphinx/pull/4328
autodoc_default_options = {"ignore-module-all": True}

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

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

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

# 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

# Output file base name for HTML help builder.
htmlhelp_basename = "bo4e-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': '',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
latex_documents = [
    (
        "index",
        "user_guide.tex",
        "bo4e Documentation",
        "Kevin Krechan",
        "manual",
    ),
]

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

# 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

# -- External mapping ---------------------------------------------------------
python_version = ".".join(map(str, sys.version_info[0:2]))
intersphinx_mapping = {
    "sphinx": ("http://www.sphinx-doc.org/en/stable", None),
    "python": ("https://docs.python.org/" + python_version, None),
}

# Create UML diagrams in plantuml format. Compile these into svg files into the _static folder.
# See docs/uml.py for more details.
release_version = Version.from_str(__gh_version__)
if not release_version.is_dirty():
    uml.LINK_URI_BASE = f"https://bo4e.github.io/BO4E-python/{__gh_version__}"
_exec_plantuml = Path(__location__) / "plantuml.jar"
_network, _namespaces_to_parse = uml.build_network(Path(module_dir), uml.PlantUMLNetwork)
print(_network)
uml.write_class_umls(_network, _namespaces_to_parse, Path(output_dir) / "uml")
print("Created uml files.")

uml.compile_files_kroki(Path(output_dir) / "uml", Path(output_dir).parent / "_static" / "images", locally_hosted=True)
print(f"Compiled uml files into svg using kroki.")

# Create compatibility matrix
# CONSOLE.verbose = True
compatibility_matrix_output_file = Path(__file__).parent / "_static/tables/compatibility_matrix.csv"
gh_token = os.getenv("GITHUB_ACCESS_TOKEN") or os.getenv("GITHUB_TOKEN") or get_access_token_from_cli_if_installed()

compiling_from_release_workflow = not release_version.is_dirty()
last_versions = get_last_n_tags(
    n=3,
    ref=str(release_version) if compiling_from_release_workflow else "HEAD",
    exclude_candidates=True,
    exclude_technical_bumps=True,
    token=gh_token,
)
schemas_base_dir = Path(__file__).parents[1] / "tmp/bo4e_json_schemas"
changes_base_dir = Path(__file__).parent / "_static/tables/changes"
current_json_schemas_dir = Path(__file__).parents[1] / "json_schemas"


async def download_missing_schemas(versions: Iterable[Version], gh_token: str | None = None) -> list[Schemas]:
    schemas_list = []
    for _version in versions:
        print(f"Checking for schemas of version {_version}...")
        schemas_dir = schemas_base_dir / str(_version)
        if not schemas_dir.exists():
            schemas_list.append(await download_schemas(_version, gh_token))
            update_references_all_schemas(schemas_list[-1])
            write_schemas(schemas_list[-1], schemas_dir)
        else:
            schemas_list.append(read_schemas(schemas_dir))
    return schemas_list


current_json_schemas = read_schemas(current_json_schemas_dir)
update_references_all_schemas(current_json_schemas)
schemas = [current_json_schemas, *asyncio.run(download_missing_schemas(last_versions, gh_token))]
changes = [diff_schemas(schemas_1, schemas_2) for schemas_1, schemas_2 in pairwise(reversed(schemas))]


def write_changes_table_csv(changes_iterable: Iterable[Changes], csv_file: Path) -> None:
    with open(csv_file, "w", encoding="utf-8") as file:
        csv_writer = csv.writer(file, delimiter=",", lineterminator="\n", escapechar="/")
        csv_writer.writerow(("Old Version", "New Version", "Diff-file"))
        for changes in changes_iterable:
            changes_file = changes_base_dir / f"{changes.old_version}_to_{changes.new_version}.json"
            write_changes(changes, changes_file)
            changes_link_path = str(changes_file.relative_to(Path(__file__).parent).as_posix())
            print(f"Created changes file: {changes_link_path}")
            csv_writer.writerow(
                (changes.old_version, changes.new_version, f"`{changes_file.name} <{changes_link_path}>`__")
            )
    print(f"Created changes table at {csv_file}")


graph = create_graph_from_changes(iter(changes))
graph_path = get_path_through_di_path_graph(graph)
compatibility_matrix = create_compatibility_matrix(graph, graph_path, use_emotes=True)
write_compatibility_matrix_csv(compatibility_matrix_output_file, compatibility_matrix, graph_path)
write_changes_table_csv(changes, compatibility_matrix_output_file.parent / "changes_table.csv")

print(f"Created compatibility matrix at static folder {compatibility_matrix_output_file}")
