# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""pytest fixtures and hooks for Debusine."""

import os
import shutil
from tempfile import TemporaryDirectory

import pytest

try:
    from pytest_django.lazy_django import django_settings_is_configured
except ImportError:  # integration tests

    def django_settings_is_configured() -> bool:
        """pytest_django has not configured Django."""
        return False


@pytest.hookimpl()
def pytest_configure() -> None:
    """Configure the Prometheus client for multi-process collection."""
    os.environ["PROMETHEUS_MULTIPROC_DIR"] = TemporaryDirectory(
        prefix="debusine-server-prometheus-multiproc-", delete=False
    ).name


@pytest.hookimpl()
def pytest_unconfigure() -> None:  # pragma: no cover
    """Clean up any paths that we created."""
    if django_settings_is_configured():
        from debusine.django.django_utils import cleanup_temp_directory

        cleanup_temp_directory()

    if "PROMETHEUS_MULTIPROC_DIR" in os.environ:
        shutil.rmtree(os.environ["PROMETHEUS_MULTIPROC_DIR"])
        del os.environ["PROMETHEUS_MULTIPROC_DIR"]
