# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# 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.
#
import os
import sys
import glob
import datetime
sys.path.append(os.getcwd())
from fortran_rst_generator import create_fortran_modules_rst, process_all_pcparam, process_bin_files, process_papers

# Import all git history
# Kishore: this unexpectedly changes the state of the user's repository if they are trying to build locally. If shallow clones are causing problems in your CI, is it not better to configure your CI to always do a full clone?
# IR: This allows for git commit references in the ReadTheDocs files, which I find useful since they link to the corresponding github files directly and you can see the history of the file
# IR: The changes in the state of the user's repository are probably due to uncommited/unstashed changes in the files. It should no happen if everything is up to date.
# IR: This was necessary to show the git history of the files in ReadTheDocs, but since I changed from automodule to autopi the custom git extensions have not been updated, so this part is not working at the moment and I am commenting it for the time being.
# IR: If this works again, you will probably have the same problem when building the documentation if your pencil directory is not up to date
# Kishore: thanks. Nevertheless, I think this will cause problems while
# Kishore: building on branches with no upstream configured (e.g. I never do my
# Kishore: development on master). Moreover, I may intentionally want to build
# Kishore: older versions of the docs locally to debug issues.
# Kishore: If readthedocs is doing a shallow clone for the build and that is
# Kishore: causing problems, you should change that in the configuration of
# Kishore: readthedocs itself, rather than an unconditional
# Kishore: `git pull --unshallow` here. In particular, you should use the
# Kishore: `post_checkout` hook described at
# Kishore: <https://docs.readthedocs.com/platform/latest/build-customization.html>
#os.system("git pull --unshallow")
#print("Git history updated")

# Path for custom-made extensions
sys.path.insert(0, os.path.abspath("./_ext"))

# Paths for autogenerated documentation, relative to .
#autopaths = ["../../python"]
autoapi_dirs = ["../../python"]
autoapi_root = "code/sourcePython"
autoapi_ignore = [
    "*pencil_old",
    "*/tests",
    "*/tutorials",
    ]

#for classes, also show the docstring of __init__
autoapi_python_class_content = "both"

#which objects to show documentation for
autoapi_options =  [
    'members',
    'undoc-members',
    'show-inheritance',
    'show-module-summary',
    'imported-members',
    ]

# keep intermediate files to allow incremental rebuilds
autoapi_keep_files = True

#for item in autopaths:
#    sys.path.insert(0, os.path.abspath(f"{item}"))

#print(sys.path)
# -- Project information -----------------------------------------------------

project = "The Pencil Code"
copyright = "2025, Illa R. Losada"
author = "Illa R. Losada"

# The short X.Y version
# version = "2.0"
# The full version, including alpha/beta/rc tags
# release = ""


# -- 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 = [
    "autoapi.extension",
    "sphinx.ext.autosectionlabel",
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.doctest",
    "sphinx.ext.todo",
    "sphinx.ext.mathjax",
    "sphinx.ext.ifconfig",
    "sphinx.ext.viewcode",
    "sphinx.ext.githubpages",
    "sphinx.ext.napoleon",
    "sphinxcontrib.images",
    "sphinxcontrib.bibtex",
    "fortran_domain",
    "fortran_autodoc",
    "sphinx.ext.intersphinx",
]

# Make sure the target of the autosection label is unique
autosectionlabel_prefix_document = True

# bibtex options
bibtex_bibfiles = ["../citations/ref.bib"]
import pencil_bibstyle
bibtex_default_style = "pencilstyle"
bibtex_reference_style = 'author_year_round'

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

# The master toctree document.
master_doc = "index"

# Turn on sphinx.ext.autosummary
autosummary_generate = True

# 
intersphinx_mapping = {
    'python': ('https://docs.python.org/3', None),
    'numpy': ('https://numpy.org/doc/stable/', None),
    'scipy': ('https://docs.scipy.org/doc/scipy/', None),
    'matplotlib': ('https://matplotlib.org/stable/', None),
}

# Inline math rendering definitions. Following the definitions used in the manual.tex

mathjax3_config = {
    "tex": {
        "inlineMath": [["$", "$"], ["\\(", "\\)"]],
        "displayMath": [["$$", "$$"], ["\\[", "\\]"]],
        "macros": {
            # ---- Operators ----
            "de": r"\mathrm{d}",
            "De": r"\mathrm{D}",
            "grad": r"\boldsymbol{\nabla}",
            "Div": r"\boldsymbol{\nabla}\!\cdot",
            "curl": r"\boldsymbol{\nabla}\!\times",
            "Laplace": r"\nabla^2",
            "rot": r"\boldsymbol{\nabla}\!\times",
            "erfc": r"\operatorname{erfc}",
            "erf": r"\operatorname{erf}",
            "const": r"\mathrm{const}",

            # ---- Derivatives ----
            "pderiv": [r"\frac{\partial #1}{\partial #2}", 2],
            "pderivn": [r"\frac{{\partial{}}^{#3} #1}{{\partial #2}^{#3}}", 3],

            # ---- Vector notation ----
            "vec": [r"\boldsymbol{#1}", 1],
            "vcs": [r"\boldsymbol{\scriptstyle{#1}}", 1],

            # ---- Common vectors ----
            "Av": r"\boldsymbol{A}",
            "Bv": r"\boldsymbol{B}",
            "Jv": r"\boldsymbol{J}",
            "Uv": r"\boldsymbol{U}",
            "Wv": r"\boldsymbol{W}",
            "Ev": r"\boldsymbol{E}",
            "Fv": r"\boldsymbol{F}",
            "fv": r"\boldsymbol{f}",
            "gv": r"\boldsymbol{g}",
            "jv": r"\boldsymbol{j}",
            "kv": r"\boldsymbol{k}",
            "ov": r"\boldsymbol{\omega}",
            "uv": r"\boldsymbol{u}",
            "vv": r"\boldsymbol{v}",
            "bv": r"\boldsymbol{b}",
            "xv": r"\boldsymbol{x}",
            "zerovect": r"\boldsymbol{0}",
            "omv": r"\boldsymbol{\omega}",
            "Bhat": r"\hat{B}",
            "BBhat": r"\hat{\boldsymbol{B}}",

            # ---- Physics symbols ----
            "Ra": r"\mathrm{Ra}",
            "Reynolds": r"\mathrm{Re}",
            "Rm": r"\mathrm{Rm}",
            "vA": r"v_{\mathrm{A}}",
            "cs": r"c_{\mathrm{s}}",
            "csnull": r"c_{{\mathrm{s}},0}",
            "Heat": r"\mathcal{H}",
            "Cool": r"\mathcal{C}",
            "Heavi": r"\theta",
            "Strain": r"\boldsymbol{\mathsf{S}}",
            "dd": r"{\rm d {}}",
            "DD": r"{\rm D {}}",
            "nab": r"{\boldsymbol \nabla {}}",
            "SSSS": r"{\boldsymbol {\sf S} {}}",
            "EEGW": r"{{\cal E}_{\rm GW}}",
            "dhT": r"{\dot{h}_+}",
            "dhX": r"{\dot{h}_\times}",
            "Shdot": r"{S_{\dot{h}}}",
            "Ahdot": r"{A_{\dot{h}}}",
            "dthT": r"{\dot{\tilde{h}}_+}",
            "dthX": r"{\dot{\tilde{h}}_\times}",
            "EGW": r"{E_{\rm GW}}",
            "HGW": r"{H_{\rm GW}}",
            "Imag": r"{\mbox{\rm Im}}",
            "DD": r"{\rm D}",
            "ii": r"{\rm i}",
            "hrms": r"{h_{\rm rms}}",
            "dhrms": r"{\dot{h}_{\rm rms}}",
            "Sh": r"{S_{h}}",
            "Ah": r"{A_{h}}",

            # ---- Brackets, averages, notation ----
            "bra": [r"\langle #1\rangle", 1],
            "Eq": [r"Eq.~(\ref{#1})", 1],
            "Fig": [r"Fig.~\ref{#1}", 1],

            # ---- Exponent helpers ----
            "EE": [r"\times 10^{#1}", 1],
            "ttimes": [r"10^{#1}", 1],
            "xtimes": [r"#1 \times 10^{#2}", 2],

            # ---- Inequality symbols ----
            "la": r"\lesssim",
            "ga": r"\gtrsim",
        }
    }
}



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

# 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 = []

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

#Option to numerate figures
numfig = True


# --- Subsitutions --------------------------
# conf.py snippet for global substitutions

# Read the _substitutions.rst content
substitutions_path = os.path.join(os.path.dirname(__file__), '_substitutions.rst')
with open(substitutions_path, encoding='utf-8') as f:
    substitutions_content = f.read()

# Add substitutions to rst_prolog so they are automatically available in all .rst files
rst_prolog = substitutions_content

# -- 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 = 'alabaster'
html_theme = "sphinx_rtd_theme"
html_logo = "pics/pencils_240x110.png"
html_title = "The Pencil Code Documentation"
html_short_title = "PCDOC"

# html_theme_path =

# 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 = {}
# import pietroalbini_sphinx_themes
# html_theme_path = [pietroalbini_sphinx_themes.themes_path()]

# html_theme = "pencil"
# html_theme_path = './pencil/'

# 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 = ['./pencil/static']
html_static_path = ["_static"]
html_css_files = ["pencil.css"]
html_js_files = ["jquery.debounce.min.js", "pencil.js"]


# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# The default sidebars (for documents that don't match any pattern) are
# defined by theme itself.  Builtin themes are using these templates by
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
# html_sidebars = {}

html_file_suffix = ".html"


# -- Options for HTMLHelp output ---------------------------------------------

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


# -- Options for LaTeX output ------------------------------------------------
#latex_engine = "pdflatex"

#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',
#}

# 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, "PCDOC.tex", "PC Documentation", "Illa R. Losada", "manual"),
    # (
    #    "manuals/quick-guide",
    #    "quickGuide.tex",
    #    "Quick start guide",
    #    "I. R. Losada, M. Lambrechts, E. Cole, P. Bourdin",
    #    "manual",
    # ),
#]


# -- 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, "pcdoc", "PC Documentation", [author], 1)]


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


# -- Options for Epub output -------------------------------------------------

# Bibliographic Dublin Core info.
epub_title = project

# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#
# epub_identifier = ''

# A unique identification for the text.
#
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ["search.html"]


# -- Extension configuration -------------------------------------------------

# -- Options for todo extension ----------------------------------------------

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

## Fortran configuration
fortran_src = create_fortran_modules_rst("../../src")
fortran_ext = ["f90"]

# Generate all rst files for the Fortran parameters table
process_all_pcparam()

# Generate list of scripts
process_bin_files()

# Generate plot and rst pages with papers
process_papers()
