Configuration Guide
===================

Comprehensive guide to configuring {{ project_name }} for your specific needs.

.. contents:: Table of Contents
   :local:
   :depth: 3

Overview
--------

{% if package_name == "pydevelop-docs" %}
{{ project_name }} provides two configuration approaches:

1. **Shared Configuration** (Recommended) - Import pre-configured settings
2. **Custom Configuration** - Full control over all Sphinx settings

Most users should start with shared configuration and customize as needed.
{% else %}
{{ project_name }} can be configured through:

- Configuration files (recommended)
- Environment variables
- Runtime parameters
- API configuration
{% endif %}

{% if package_name == "pydevelop-docs" %}
Shared Configuration (Recommended)
-----------------------------------

The easiest way to configure documentation with all 40+ extensions pre-configured.

**Basic Setup:**

.. code-block:: python

   # docs/source/conf.py
   from pydevelop_docs.config import get_haive_config
   
   # Get standardized configuration
   config = get_haive_config(
       project_name="{{ project_name }}",
       package_path="/path/to/your/package"
   )
   
   # Apply all settings
   for key, value in config.items():
       if key not in ['project', 'copyright', 'author', 'release']:
           globals()[key] = value

**What You Get:**

✅ 40+ Sphinx extensions pre-configured
✅ Hierarchical AutoAPI (not flat!)
✅ Beautiful Furo theme with dark mode
✅ All extension compatibility issues resolved
✅ Performance optimizations
✅ Mobile-responsive design

**Quick Customization:**

.. code-block:: python

   # Get base config
   config = get_haive_config("myproject", "/path/to/src")
   
   # Customize before applying
   config["html_theme"] = "sphinx_rtd_theme"
   config["autoapi_options"].append("special-members")
   config["html_theme_options"]["navigation_depth"] = 5
   
   # Apply customized config
   for key, value in config.items():
       globals()[key] = value

Core Configuration Options
--------------------------

**Project Information:**

.. code-block:: python

   # Required project metadata
   project = "{{ project_name }}"
   author = "Your Team"
   copyright = "2025, Your Team"
   release = "1.0.0"
   version = "1.0"

**Extensions Configuration:**

.. code-block:: python

   # Essential extensions (included in shared config)
   extensions = [
       "autoapi.extension",           # Automatic API docs
       "sphinx.ext.autodoc",          # Manual API docs
       "sphinx.ext.napoleon",         # Google/NumPy docstrings
       "sphinx.ext.viewcode",         # Source code links
       "sphinx.ext.intersphinx",      # Cross-project links
       "myst_parser",                 # Markdown support
       "sphinx_design",               # Beautiful UI components
       "sphinx_copybutton",           # Copy code buttons
       "sphinxcontrib.mermaid",       # Diagrams
       # ... 30+ more included automatically
   ]

AutoAPI Configuration
---------------------

**Hierarchical Structure (The Magic Setting!):**

.. code-block:: python

   # This transforms flat API docs into beautiful hierarchy
   autoapi_own_page_level = "module"  # ← This is the key!
   
   autoapi_options = [
       "members",                 # Include all members
       "undoc-members",          # Include undocumented
       "show-inheritance",       # Show class inheritance
       "show-module-summary",    # Enable hierarchical grouping
       "private-members",        # Include private members
   ]

**Package Discovery:**

.. code-block:: python

   # Point to your source code
   autoapi_dirs = [
       "src/mypackage",          # Single package
       # or for monorepo:
       "packages/package1/src",
       "packages/package2/src",
   ]
   
   # Advanced options
   # autoapi_template_dir = "_autoapi_templates"  # Custom templates (not recommended)
   autoapi_add_toctree_entry = True               # Add to main TOC
   autoapi_member_order = "groupwise"             # Group by type
   autoapi_own_page_level = "module"              # Hierarchical organization (recommended)

Theme Configuration
-------------------

**Furo Theme (Default):**

.. code-block:: python

   html_theme = "furo"
   html_theme_options = {
       # Navigation
       "navigation_depth": 4,
       "collapse_navigation": False,
       "sticky_navigation": True,
       "includehidden": True,
       
       # Appearance
       "sidebar_hide_name": True,
       "navigation_with_keys": True,
       "top_of_page_button": "edit",
       
       # Dark mode support (automatic)
       "dark_css_variables": {
           "--color-brand-primary": "#2196F3",
           "--color-brand-content": "#1976D2",
       },
   }

**Alternative Themes:**

.. tab-set::

    .. tab-item:: Sphinx RTD Theme

        .. code-block:: python

            html_theme = "sphinx_rtd_theme"
            html_theme_options = {
                "navigation_depth": 4,
                "collapse_navigation": False,
                "sticky_navigation": True,
                "logo_only": False,
                "display_version": True,
            }

    .. tab-item:: PyData Theme

        .. code-block:: python

            html_theme = "pydata_sphinx_theme"
            html_theme_options = {
                "navbar_start": ["navbar-logo"],
                "navbar_center": ["navbar-nav"],
                "navbar_end": ["navbar-icon-links"],
                "navbar_persistent": ["search-button"],
            }

    .. tab-item:: Book Theme

        .. code-block:: python

            html_theme = "sphinx_book_theme"
            html_theme_options = {
                "repository_url": "https://github.com/your-org/your-repo",
                "use_repository_button": True,
                "use_issues_button": True,
                "use_download_button": True,
            }

{% endif %}

Advanced Configuration
----------------------

{% if package_name == "pydevelop-docs" %}
**Monorepo Configuration:**

.. code-block:: python

   # Multi-package documentation
   autoapi_dirs = [
       "packages/core/src",
       "packages/agents/src", 
       "packages/tools/src",
   ]
   
   # Central hub linking
   html_context = {
       "hub_packages": [
           {"name": "core", "path": "../core/"},
           {"name": "agents", "path": "../agents/"},
           {"name": "tools", "path": "../tools/"},
       ]
   }

**Custom CSS/JS:**

.. code-block:: python

   # Add custom styling
   html_static_path = ["_static"]
   html_css_files = [
       "css/custom.css",
       "css/dark-mode-fixes.css",
   ]
   
   html_js_files = [
       "js/api-enhancements.js",
   ]
{% endif %}

**Intersphinx Mapping:**

.. code-block:: python

   # Link to external documentation
   intersphinx_mapping = {
       "python": ("https://docs.python.org/3", None),
       "sphinx": ("https://www.sphinx-doc.org/en/master", None),
       "pydantic": ("https://docs.pydantic.dev/latest", None),
       {% if package_name == "pydevelop-docs" %}
       # Auto-populated from pyproject.toml by seed-intersphinx-mapping
       {% endif %}
   }

**MyST (Markdown) Support:**

.. code-block:: python

   # Enhanced Markdown features
   myst_enable_extensions = [
       "colon_fence",      # ::: code blocks
       "deflist",          # Definition lists  
       "fieldlist",        # Field lists
       "html_admonition",  # HTML-style admonitions
       "html_image",       # HTML images
       "linkify",          # Auto-link URLs
       "replacements",     # Text replacements
       "smartquotes",      # Smart quotes
       "strikethrough",    # ~~strikethrough~~
       "substitution",     # Variable substitution
       "tasklist",         # - [ ] Task lists
   ]

Environment Variables
---------------------

{% if package_name == "pydevelop-docs" %}
Configure {{ project_name }} behavior through environment variables:

.. list-table::
   :header-rows: 1
   :widths: 30 70

   * - Variable
     - Description
   * - ``PYDEVELOP_DOCS_THEME``
     - Override default theme (e.g., ``sphinx_rtd_theme``)
   * - ``PYDEVELOP_DOCS_DEBUG``  
     - Enable debug output (``true`` or ``false``)
   * - ``PYDEVELOP_DOCS_PARALLEL``
     - Control parallel building (``auto``, ``1-8``)
   * - ``PYDEVELOP_DOCS_BUILDER``
     - Default builder (``html``, ``pdf``, ``epub``)

**Usage:**

.. code-block:: bash

   # Use different theme
   export PYDEVELOP_DOCS_THEME=sphinx_rtd_theme
   pydevelop-docs build
   
   # Enable debug mode
   export PYDEVELOP_DOCS_DEBUG=true
   pydevelop-docs init --dry-run
{% endif %}

Common Customizations
---------------------

**Adding Custom Extensions:**

.. code-block:: python

   # Add to existing extensions
   extensions.extend([
       "sphinx_click",           # CLI documentation
       "sphinxcontrib.openapi",  # OpenAPI specs
       "sphinx_external_toc",    # External TOC
   ])

**Custom Code Block Styling:**

.. code-block:: python

   # Syntax highlighting
   pygments_style = "sphinx"
   pygments_dark_style = "monokai"  # Dark mode
   
   # Code block options
   highlight_language = "python"
   highlight_options = {
       "stripnl": False,
       "stripall": False,
   }

**PDF Output (LaTeX):**

.. code-block:: python

   # LaTeX configuration for PDF
   latex_elements = {
       "papersize": "letterpaper",
       "pointsize": "10pt",
       "preamble": r"\usepackage{sphinx}",
   }
   
   latex_documents = [(
       "index",               # Source start file
       "{{ package_name }}.tex",  # Target name
       "{{ project_name }} Documentation",  # Title
       "Your Team",           # Author
       "manual",              # Document class
   )]

Real-World Examples
-------------------

**Example 1: API-Heavy Project**

.. code-block:: python

   # Focus on API documentation
   autoapi_options = [
       "members", "undoc-members", "show-inheritance",
       "show-module-summary", "special-members",
   ]
   
   # Detailed API display
   autodoc_default_options = {
       "members": True,
       "inherited-members": True,
       "show-inheritance": True,
   }

**Example 2: Tutorial-Heavy Project**

.. code-block:: python

   # Emphasis on narrative documentation
   html_theme_options.update({
       "navigation_depth": 3,
       "collapse_navigation": True,  # Collapse API sections
   })
   
   # Custom TOC structure
   html_sidebars = {
       "**": [
           "sidebar/brand.html",
           "sidebar/search.html", 
           "sidebar/navigation.html",
       ]
   }

{% if package_name == "pydevelop-docs" %}
**Example 3: Monorepo Documentation Hub**

.. code-block:: python

   # Central hub configuration
   autoapi_dirs = []  # No API docs in hub
   
   # Link to package docs
   html_context = {
       "packages": [
           {"name": "Core", "url": "../core/"},
           {"name": "Agents", "url": "../agents/"},
           {"name": "Tools", "url": "../tools/"},
       ]
   }
   
   # Custom templates for hub
   templates_path = ["_templates/hub"]
{% endif %}

Troubleshooting Configuration
-----------------------------

**Common Issues:**

.. tab-set::

    .. tab-item:: Extension Conflicts

        .. code-block:: python

            # Check extension loading order
            extensions = [
                "autoapi.extension",      # Must be first
                # ... other extensions
                "sphinx_toolbox",         # Before sphinx_autodoc_typehints
                "sphinx_autodoc_typehints",  # Must be after sphinx_toolbox
            ]

    .. tab-item:: Import Errors

        .. code-block:: bash

            # Ensure package is importable
            python -c "import your_package"
            
            # Check PYTHONPATH
            export PYTHONPATH=/path/to/your/src:$PYTHONPATH

    .. tab-item:: Build Warnings

        .. code-block:: bash

            # Build with detailed warnings
            sphinx-build -b html source build -W --keep-going -v

**Debug Mode:**

.. code-block:: bash

   # Enable Sphinx debug output
   sphinx-build -b html source build -v -v -v
   
   {% if package_name == "pydevelop-docs" %}
   # PyDevelop-Docs debug mode
   export PYDEVELOP_DOCS_DEBUG=true
   pydevelop-docs build
   {% endif %}

**Configuration Validation:**

.. code-block:: python

   # Add to conf.py for debugging
   def setup(app):
       """Sphinx setup hook for debugging."""
       print(f"Extensions loaded: {app.config.extensions}")
       print(f"AutoAPI dirs: {app.config.autoapi_dirs}")
       print(f"Theme: {app.config.html_theme}")

Migration from Other Tools
--------------------------

{% if package_name == "pydevelop-docs" %}
**From Sphinx-AutoDoc:**

.. code-block:: python

   # Old way (manual)
   extensions = ["sphinx.ext.autodoc"]
   
   # New way (automatic)
   from pydevelop_docs.config import get_haive_config
   config = get_haive_config("myproject", "/path/to/src")

**From MkDocs:**

1. Copy content from ``docs/`` to ``docs/source/``
2. Convert ``*.md`` files (MyST handles most syntax)
3. Replace ``mkdocs.yml`` with ``conf.py``
4. Run ``pydevelop-docs init`` for full setup
{% endif %}

**From Plain Sphinx:**

1. Backup existing ``conf.py``
2. Run ``{{ package_name }} init`` to generate new config
3. Merge custom settings from backup
4. Test build and adjust as needed

Best Practices
--------------

**Performance:**

- Use ``autoapi_own_page_level = "module"`` for better organization
- Enable parallel builds: ``sphinx-build -j auto``
- {% if package_name == "pydevelop-docs" %}Use shared config to avoid extension conflicts{% endif %}

**Maintainability:**

- Document your customizations in comments
- Use version control for ``conf.py``
- Test builds in CI/CD
- Keep extensions up to date

**User Experience:**

- Enable search functionality
- Use clear navigation structure
- Add cross-references between sections
- Include examples and tutorials

Getting Help
------------

**Configuration Issues:**

{# djlint:off H025 #}
1. Check the `configuration examples <https://github.com/{{ github_org }}/{{ github_repo }}/tree/main/examples>`_
2. Search `GitHub issues <https://github.com/{{ github_org }}/{{ github_repo }}/issues?q=configuration>`_
3. Ask in `discussions <https://github.com/{{ github_org }}/{{ github_repo }}/discussions>`_
{# djlint:on #}

**Next Steps:**

- 🚀 **Quick Start**: :doc:`quickstart` - Get up and running
- 📖 **Installation**: :doc:`installation` - Detailed setup
- 💡 **Examples**: :doc:`../examples/index` - Real-world configurations
- 🎯 **Tutorials**: :doc:`../tutorials/first_steps` - Step-by-step guides

.. tip::
   **Pro Tip**: Start with shared configuration and only customize what you need. Most projects work great with the defaults!