# License: 3-clause BSD
"""Test the SG pipeline using Sphinx and tinybuild."""

import shutil
from io import StringIO
from pathlib import Path

import pytest
from sphinx.application import Sphinx
from sphinx.util.docutils import docutils_namespace


@pytest.fixture(scope="module")
def sphinx_app(tmp_path_factory, req_mpl, req_pil):
    temp_dir = tmp_path_factory.getbasetemp() / "root_nonexec"
    src_dir = Path(__file__).parent / "tinybuild"

    def ignore(src, names):
        return ("_build", "gen_modules", "auto_examples")

    shutil.copytree(src_dir, temp_dir, ignore=ignore)
    # For testing iteration, you can get similar behavior just doing `make`
    # inside the tinybuild/doc directory
    src_dir = temp_dir
    conf_dir = temp_dir / "doc"
    out_dir = conf_dir / "_build" / "html"
    toctrees_dir = temp_dir / "doc" / "_build" / "toctrees"
    # Avoid warnings about re-registration, see:
    # https://github.com/sphinx-doc/sphinx/issues/5038
    confoverrides = {
        "sphinx_gallery_conf.plot_gallery": 0,
    }
    with docutils_namespace():
        app = Sphinx(
            conf_dir,
            conf_dir,
            out_dir,
            toctrees_dir,
            buildername="html",
            confoverrides=confoverrides,
            status=StringIO(),
            warning=StringIO(),
        )
        # need to build within the context manager
        # for automodule and backrefs to work
        app.build(False, [])
    return app


def test_dummy_image(sphinx_app):
    """Test that sphinx_gallery_dummy_images are created."""
    img1 = Path(
        sphinx_app.srcdir, "auto_examples", "images", "sphx_glr_plot_repr_001.png"
    )
    img2 = Path(
        sphinx_app.srcdir, "auto_examples", "images", "sphx_glr_plot_repr_002.png"
    )
    assert img1.is_file()
    assert img2.is_file()
