import sys
from pathlib import Path
from datetime import datetime
import importlib.metadata
import email.policy

sys.path.insert(0, str(Path('..', 'src').resolve()))

# 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

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = 'Utilities'

package_name = 'sieve_utils'

# Extract metadata from the package
try:
    metadata = importlib.metadata.metadata(package_name)
except importlib.metadata.PackageNotFoundError:
    raise RuntimeError(f"Package {package_name} not found.")

# Extract author name(s) from 'Author-email' field ('Author' field not always present when using pyproject.toml)
em = email.message_from_string(f"To: {metadata['Author-email']}", policy=email.policy.default)
author_names = [a.display_name for a in em['To'].addresses]
if not author_names:
    raise RuntimeError(f"Author name(s) not able to be extracted from {metadata['Author-email']}")
if len(author_names) == 1:
    author = author_names[0]
elif len(author_names) == 2:
    author = " and ".join(author_names)
else:
    author = ", ".join(author_names[:-1]) + f", and {author_names[-1]}"

# Extract version, release, and copyright
version = metadata["Version"]
release = metadata["Version"]
copyright = f"{datetime.now().year}, {author}"

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

extensions = ['sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.napoleon']
autosummary_generate = True
autosummary_generate_overwrite = True
autosummary_output_dir = "_autosummary"  # Force output to a single directory

# Autodoc settings
autodoc_default_options = {
    'members': True,           # Document all members
    'undoc-members': True,     # Include undocumented members
    'inherited-members': True, # Show inherited members
    'show-inheritance': True,
    'special-members': '__init__',  # Include __init__ docstrings
    'member-order': 'bysource',  # Preserve function order as written in code
    'exclude-members': '__weakref__',
}

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