# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

import os
import sys
import datetime
import re
from pathlib import Path

# Add project root to the path so sphinx can find the modules to document
sys.path.insert(0, os.path.abspath(".."))

# -- Project information from pyproject.toml -----------------------------------

# Try to read from pyproject.toml
pyproject_path = Path(__file__).parent.parent / "pyproject.toml"
if pyproject_path.exists():
    try:
        # Python 3.11+ has tomllib in the standard library
        try:
            import tomllib
        except ImportError:
            import tomli as tomllib

        with open(pyproject_path, "rb") as f:
            pyproject_data = tomllib.load(f)

        # Extract project name
        if "name" in pyproject_data.get("project", {}):
            project = pyproject_data["project"]["name"]

        # Extract version
        if "version" in pyproject_data.get("project", {}):
            version = pyproject_data["project"]["version"]
            release = version

        # Extract authors
        if "authors" in pyproject_data.get("project", {}):
            # Handle different author formats
            authors_data = pyproject_data["project"]["authors"]
            author_names = []

            for author_entry in authors_data:
                if isinstance(author_entry, dict) and "name" in author_entry:
                    author_names.append(author_entry["name"])
                elif isinstance(author_entry, str):
                    author_names.append(author_entry)

            if author_names:
                author = ", ".join(author_names)
    except Exception as e:
        print(f"Warning: Could not extract metadata from pyproject.toml: {e}")
        # Fall back to defaults defined above

# Set copyright with current year
copyright = f"{datetime.datetime.now().year}, {author}"

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.napoleon",  # Support for NumPy and Google style docstrings
    "sphinx.ext.viewcode",  # Add links to view source code
    "sphinx.ext.mathjax",  # Support for math equations
    "sphinx.ext.intersphinx",  # Link to other projects' documentation
    "sphinx.ext.autosummary",  # Generate autodoc summaries
    "sphinx_rtd_theme",  # Read the Docs theme
    "myst_parser",  # Support for Markdown files
    "nbsphinx",  # Support for Jupyter notebooks
]

# Configure MyST-Parser for Markdown support
myst_enable_extensions = [
    "amsmath",
    "colon_fence",
    "deflist",
    "dollarmath",
    "html_image",
    "linkify",
    "smartquotes",
    "substitution",
    "tasklist",
]

# Add any Markdown files you want parsed
source_suffix = {
    ".rst": "restructuredtext",
    ".md": "markdown",
}

templates_path = ["_templates"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = "sphinx_rtd_theme"
html_static_path = ["_static"]
html_logo = None  # Add logo path if available

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

# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_preprocess_types = False
napoleon_type_aliases = None
napoleon_attr_annotations = True

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

# Autodoc settings
autodoc_default_options = {
    "members": True,
    "member-order": "bysource",
    "special-members": "__init__",
    "undoc-members": True,
    "exclude-members": "__weakref__",
}

# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
    # The paper size ('letterpaper' or 'a4paper')
    "papersize": "letterpaper",
    # Additional stuff for the LaTeX preamble
    "preamble": r"""
    \usepackage{amsmath}
    \usepackage{amssymb}
    \usepackage{amsfonts}
    """,
}

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    "sphinx.ext.autodoc",
    "sphinx.ext.napoleon",  # Support for NumPy and Google style docstrings
    "sphinx.ext.viewcode",  # Add links to view source code
    "sphinx.ext.mathjax",  # Support for math equations
    "sphinx.ext.intersphinx",  # Link to other projects' documentation
    "sphinx.ext.autosummary",  # Generate autodoc summaries
    "sphinx_rtd_theme",  # Read the Docs theme
    "myst_parser",  # Support for Markdown files
    "nbsphinx",  # Support for Jupyter notebooks
]

# Configure MyST-Parser for Markdown support
myst_enable_extensions = [
    "amsmath",
    "colon_fence",
    "deflist",
    "dollarmath",
    "html_image",
    "linkify",
    "smartquotes",
    "substitution",
    "tasklist",
]
