"""Pytest config for the mgf.django test suite.

Configures Django settings BEFORE Django is imported by any test
or by mgf.django itself. Without this, ``django.conf``
construction races with the test setup.
"""

from __future__ import annotations

import pytest


@pytest.fixture(autouse=True)
def _ensure_bootstrap():
    """Re-bootstrap if a sibling test wiped the global context.

    Django's ``MgfCommonConfig.ready()`` calls bootstrap once and
    expects it to live for the process lifetime. Some tests
    deliberately shut down + replace the global context. This
    fixture re-runs Django's bootstrap if the suite has wiped it.
    """
    from mgf.common._lifecycle import current_context

    from mgf.django import _apps

    if current_context() is None:
        # Reset the guard so ready() actually does its work.
        with _apps._BOOTSTRAP_LOCK:
            _apps._BOOTSTRAP_STACK = None
        from django.apps import apps as django_apps

        django_apps.get_app_config("mgf_django").ready()
    yield


@pytest.fixture(scope="package", autouse=True)
def _restore_identity_after_django_package():
    """Tear down Django's open bootstrap stack at end of package.

    Django's :class:`MgfCommonConfig` keeps the bootstrap context
    manager open on a module-level :class:`ExitStack` for the
    process lifetime, so identity (``_APP_NAME = "test-app"`` here)
    leaks into later test files. Closing the stack at end-of-package
    triggers bootstrap's rollback, which restores ``_APP_NAME`` /
    ``_APP_VERSION`` to whatever they were before this package ran.
    """
    yield
    from mgf.django import _apps

    _apps._cleanup_bootstrap()


def pytest_configure(config):
    import django
    from django.conf import settings as django_settings

    if django_settings.configured:
        return

    django_settings.configure(
        DEBUG=False,
        SECRET_KEY="test-secret-key-not-for-production",
        ALLOWED_HOSTS=["*"],
        INSTALLED_APPS=[
            "django.contrib.contenttypes",
            "django.contrib.auth",
            "mgf.django",
        ],
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.sqlite3",
                "NAME": ":memory:",
            },
        },
        TIME_ZONE="UTC",
        USE_TZ=True,
        LANGUAGE_CODE="en-us",
        ROOT_URLCONF="tests.unit._urls",
        MIDDLEWARE=[
            "mgf.django.MgfRequestIdMiddleware",
            "mgf.django.MgfContextMiddleware",
        ],
        MGF_COMMON_APP_NAME="test-app",
        MGF_COMMON_APP_VERSION="0.0.1",
    )
    django.setup()
