"""PC-02: ``MgfCommonConfig.ready()`` bootstrap wall-clock pin.

`MgfCommonConfig.ready()` runs once per process during Django's
app-registry build:

  1. Acquire `_BOOTSTRAP_LOCK`.
  2. Read two Django settings (`MGF_COMMON_APP_NAME`, `..._VERSION`).
  3. Build `ExitStack`.
  4. Call `mgf.common.bootstrap(...)` — transitively touches the
     redactor patterns, JSON formatter, stderr handler, rotating-
     file handler, OTel setup, excepthook installers.
  5. Register `atexit` hook for clean shutdown.

For long-lived workers (`runserver`, gunicorn) the cost amortises
to zero; for short-lived processes (`manage.py migrate`, test
runners, `manage.py` one-shot commands) every invocation pays it.

Methodology: fork a fresh Python subprocess, configure Django,
call `django.setup()` which triggers `AppConfig.ready()` for
every entry in `INSTALLED_APPS` including `mgf.django`. Measure
wall-clock. Repeat 5x; take the median.

Local baseline (Linux 6.17, Python 3.11, v0.2.0): ~174 ms median.
Budget: 500 ms — ~2.9x cushion to absorb CI noise + slower
hardware + mgf-common changes upstream.

Marker: ``perf`` (registered in pyproject.toml). Excluded from
the default suite; run via ``pytest -m perf`` for the nightly
sweep.
"""

from __future__ import annotations

import subprocess
import sys
import textwrap
import time

import pytest

# Bootstrap wall-clock budget. The measurement includes Python
# startup, Django's settings.configure + django.setup, and mgf.django's
# AppConfig.ready() — so the budget reflects total cold-start cost,
# not the bootstrap step in isolation. A breach signals either a
# mgf.django regression OR an upstream mgf-common cold-import regression
# (see mgf-common PC-01 for the cornerstone baseline).
_BOOTSTRAP_BUDGET_MS = 500.0

_BOOTSTRAP_SCRIPT = textwrap.dedent(
    """
    import django
    from django.conf import settings

    settings.configure(
        DEBUG=False,
        SECRET_KEY="perf-test-secret",
        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",
        MIDDLEWARE=[],
        MGF_COMMON_APP_NAME="perf-test",
        MGF_COMMON_APP_VERSION="0.0.1",
    )
    django.setup()
    """
)


@pytest.mark.perf
class TestBootstrapTime:
    """Pin the Django + mgf.django cold-start wall-clock."""

    def test_bootstrap_under_budget(self) -> None:
        """Median of 5 fresh-subprocess bootstraps stays under budget.

        Why median-of-5: the first run pays first-time filesystem-cache
        costs and CI runners can drop noisy outliers on either end.
        The median value is stable + meaningful.
        """
        runs: list[float] = []
        for _ in range(5):
            start = time.perf_counter()
            subprocess.run(
                [sys.executable, "-c", _BOOTSTRAP_SCRIPT],
                check=True,
            )
            runs.append((time.perf_counter() - start) * 1000.0)

        runs.sort()
        median_ms = runs[2]

        assert median_ms < _BOOTSTRAP_BUDGET_MS, (
            f"PC-02: Django + mgf.django bootstrap budget breach: "
            f"median {median_ms:.0f} ms over 5 runs (budget "
            f"{_BOOTSTRAP_BUDGET_MS:.0f} ms). "
            f"All runs: {[f'{r:.0f}' for r in runs]} ms. "
            f"Investigate src/mgf/django/_apps.py::MgfCommonConfig.ready "
            f"+ cross-check mgf-common PC-01 (cold-import) for upstream "
            f"regression."
        )
