# -*- coding: utf-8 -*-
#
# InVEST 3 documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 12 11:08:28 2014.
#
# 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.

from datetime import datetime
import importlib
import os
import pkgutil
import sys
from unittest.mock import MagicMock

import natcap.invest
from sphinx.ext import apidoc

DOCS_SOURCE_DIR = os.path.dirname(__file__)
# get the directory that the natcap package lives in
INVEST_LIB_DIR = os.path.dirname(os.path.dirname(natcap.invest.__file__))

# -- 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.mathjax',
    'sphinx.ext.napoleon',
]

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

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

# The master toctree document.
master_doc = 'index'

# General information about the project.
project = 'InVEST'
copyright = f'{datetime.now().year}, The Natural Capital Project'

# The full version, including alpha/beta/rc tags.
release = natcap.invest.__version__
version = release.split('+')[0]

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

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

# If true, keep warnings as "system message" paragraphs in the built documents.
keep_warnings = False


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

import sphinx_rtd_theme

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'

# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/invest-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/favicon.gif"

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

# Output file base name for HTML help builder.
htmlhelp_basename = 'InVESTdoc'

# -- Options for LaTeX output ---------------------------------------------

# 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 = [
  ('index', 'InVEST.tex', 'InVEST Documentation',
   'The Natural Capital Project', 'manual'),
]


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    ('index', 'invest', 'InVEST Documentation',
     ['The Natural Capital Project'], 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 = [
  ('index', 'InVEST', 'InVEST Documentation',
   'The Natural Capital Project', 'InVEST',
   'Integrated Valuation of Ecosystem Services and Tradeoffs',
   'Scientific Software'),
]


# -- Prepare for sphinx build ---------------------------------------------

# Use sphinx apidoc tool to generate documentation for invest. Generated rst
# files go into the api/ directory. Note that some apidoc options may not work
# the same because we aren't using their values in the custom templates
apidoc.main([
    '--force',  # overwrite any files from previous run
    '-o', os.path.join(DOCS_SOURCE_DIR, 'api'),  # output to api/
    '--templatedir', os.path.join(DOCS_SOURCE_DIR, 'templates'),  # use custom templates
    '--separate',  # make a separate page for each module
    '--no-toc',  # table of contents page is redundant
    '--implicit-namespaces',
    INVEST_LIB_DIR,
    '/*.so'  # must be absolute path, see https://github.com/sphinx-doc/sphinx/issues/10200
])


# -- Generate model entrypoints file --------------------------------------

MODEL_RST_TEMPLATE = """
.. _models:

=========================
InVEST Model Entry Points
=========================

All InVEST models share a consistent python API:

    - Every InVEST model has a corresponding module or subpackage in the
      ``natcap.invest`` package
    - The model modules contain a function called ``execute``
    - The ``execute`` function takes a single argument (``args``), a dictionary
      that stores all data inputs and configuration options for the model
    - This dictionary contains an entry, ``'workspace_dir'``, which is a path
      to the folder where the model will create its output files
    - Other required and optional entries in the dictionary are specific to
      each model

To run a model, import the model's ``execute`` function and then call it with
the correct parameters. For example, a script for the Carbon model might look
like

.. code-block:: python

    import natcap.invest.carbon
    args = {
        'workspace_dir': 'path/to/workspace'
        # Other arguments, as needed for Carbon.
    }

    natcap.invest.carbon.execute(args)

For examples of scripting a model run, or multiple successive model runs,
see :ref:`CreatingPythonScripts`.


.. contents:: Available Models and Tools:
    :local:

"""

MODEL_ENTRYPOINTS_FILE = os.path.join(DOCS_SOURCE_DIR, 'models.rst')
# Find all importable modules with an execute function
# write out to a file models.rst in the source directory
invest_model_modules = {}
for _, name, _ in pkgutil.walk_packages(path=[INVEST_LIB_DIR],
                                        prefix='natcap.'):
    module = importlib.import_module(name)
    # any module with a MODEL_SPEC is an invest model
    if hasattr(module, 'MODEL_SPEC'):
        model_title = module.MODEL_SPEC['model_name']
        invest_model_modules[model_title] = name

# Write sphinx autodoc function for each entrypoint
with open(MODEL_ENTRYPOINTS_FILE, 'w') as models_rst:
    models_rst.write(MODEL_RST_TEMPLATE)
    for model_title, name in sorted(invest_model_modules.items()):
        underline = ''.join(['=']*len(model_title))
        models_rst.write(
            f'{model_title}\n'
            f'{underline}\n'
            f'.. autofunction:: {name}.execute\n'
            '   :noindex:\n\n')
