import os
from importlib import metadata
from pathlib import Path

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

# General information about the project.
project = "acore"
copyright = "2026, Multi-omics Network Analytics Group"
author = "Multi-omics Network Analytics Group, Sebastián Ayala Ruano, Henry Webel, Alberto Santos"
PACKAGE_VERSION = metadata.version("acore")
version = PACKAGE_VERSION
release = PACKAGE_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"

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


# 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.autosectionlabel",
    "sphinx.ext.autodoc",
    "sphinx.ext.autodoc.typehints",
    "sphinx.ext.napoleon",
    # "sphinx.ext.doctest",
    "sphinx.ext.intersphinx",
    # "sphinx.ext.autosummary",
    # "sphinx.ext.mathjax",
    # "sphinx.ext.coverage",
    # "sphinx.ext.imgmath",
    # "sphinx.ext.ifconfig",
    "sphinx.ext.viewcode",
    "sphinx_new_tab_link",
    "myst_nb",
    "sphinx_copybutton",
]

myst_enable_extensions = [
    # "strikethrough",
    "dollarmath",
    "amsmath",
    "colon_fence",
]

#  https://myst-nb.readthedocs.io/en/latest/computation/execute.html
nb_execution_mode = "auto"

# https://myst-nb.readthedocs.io/en/latest/configuration.html
# Execution
nb_execution_raise_on_error = True
# Rendering
nb_merge_streams = True
# maximum execution time per cell in seconds
nb_execution_timeout = 120

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

# 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",
    "jupyter_execute",
    "conf.py",
    "fetch_files.py",
]


# Intersphinx options
intersphinx_mapping = {
    "python": ("https://docs.python.org/3", None),
    "numpy": ("https://numpy.org/doc/stable/", None),
    "pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None),
    "pandera": ("https://pandera.readthedocs.io/en/stable/", None),
    "pydantic": ("https://docs.pydantic.dev/latest", None),
    # "scikit-learn": ("https://scikit-learn.org/stable/", None),
    # "matplotlib": ("https://matplotlib.org/stable/", None),
}


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

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

autosectionlabel_prefix_document = True

## Include Python objects as they appear in source files
## Default: alphabetically ('alphabetical')
autodoc_member_order = "bysource"
## Default flags used by autodoc directives
autodoc_default_options = {
    "members": True,
    "show-inheritance": True,
    "undoc-members": True,
    "inherited-members": "BaseModel",
}

## Generate autodoc stubs with summaries from code
autosummary_generate = True

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

myst_enable_extensions = ["dollarmath", "amsmath", "colon_fence"]

# Plolty support through require javascript library
# https://myst-nb.readthedocs.io/en/latest/render/interactive.html#plotly
html_js_files = [
    # "https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.7/require.min.js",
    # https://plotly.com/javascript/getting-started/
    "https://cdn.plot.ly/plotly-3.0.1.min.js",
]


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
# See:
# https://github.com/executablebooks/MyST-NB/blob/master/docs/conf.py
# html_title = ""
html_theme = "sphinx_book_theme"
html_logo = "images/logo/acore_logo.svg"
html_favicon = "images/logo/acore_logo_small.svg"
html_theme_options = {
    "github_url": "https://github.com/Multiomics-Analytics-Group/acore/",
    "repository_url": "https://github.com/Multiomics-Analytics-Group/acore/",
    "repository_branch": "main",
    "home_page_in_toc": True,
    "path_to_docs": "docs",
    "show_navbar_depth": 1,
    "use_edit_page_button": True,
    "use_repository_button": True,
    "use_download_button": True,
    "launch_buttons": {
        "colab_url": "https://colab.research.google.com"
        #     "binderhub_url": "https://mybinder.org",
        #     "notebook_interface": "jupyterlab",
    },
    "navigation_with_keys": False,
}
# 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']

# -- Setup for sphinx-apidoc -------------------------------------------------

# sphinx-apidoc needs to be called manually if Sphinx is running there.
# https://github.com/readthedocs/readthedocs.org/issues/1139

if os.environ.get("READTHEDOCS") == "True":
    # Set the Plotly renderer to notebook for ReadTheDocs (visualize plotly figures
    # in the documentation) - needed for plotly6
    # Plotly normally decides itself fine which renderer to use, so keep it to RTD
    # see https://plotly.com/python/renderers/#setting-the-default-renderer
    os.environ["PLOTLY_RENDERER"] = "notebook"

    PROJECT_ROOT = Path(__file__).parent.parent
    PACKAGE_ROOT = PROJECT_ROOT / "src" / "acore"

    def run_split_readme(_):
        print("[conf.py] Splitting README.md into sections...")
        from split_readme import process_readme

        readme_path = PROJECT_ROOT / "README.md"
        output_dir = PROJECT_ROOT / "docs" / "sections_readme"
        process_readme(readme_path, output_dir)

    def run_apidoc(_):
        from sphinx.ext import apidoc

        apidoc.main(
            [
                "--force",
                "--implicit-namespaces",
                "--module-first",
                "--separate",
                "-o",
                str(PROJECT_ROOT / "docs" / "reference"),
                str(PACKAGE_ROOT),
                str(PACKAGE_ROOT / "*.c"),
                str(PACKAGE_ROOT / "*.so"),
            ]
        )

    def download_notebooks(_):
        from fetch_files import download_notebook

        # Download the notebook file
        download_notebook(
            repo_url_base="https://github.com/biosustain/dsp_course_proteomics_intro",
            file_path_in_repo="2_data_analysis.ipynb",
            output_path="downloaded/PXD040621_analysis.ipynb",
        )

    def setup(app):
        app.connect("builder-inited", run_split_readme)
        app.connect("builder-inited", run_apidoc)
        app.connect("builder-inited", download_notebooks)
