"""PAPER-23 honesty probe — the pytest-plugin silence gets LOUD.

The ``pytest11`` entry point auto-loads ``mgf.common.pytest_plugin``
for wheel-installed consumers. But an editable install wired via
``[tool.uv.sources]`` (or any tool that skips writing the dist-info
``entry_points.txt``) leaves the plugin silently unloaded: fixtures
vanish, ``--mgf-perf`` / ``MGF_PERF`` capture no-ops, and everything
still exits 0 — a quiet hole in the test story (PAPER-23; PLAN M2
Wave-2 §1.5).

This probe closes the silence: when ``mgf.common`` is imported (or
:func:`mgf.common.bootstrap_for_test` runs) INSIDE a live pytest test
while the plugin module was never loaded AND no ``pytest11`` entry
point for mgf-common is visible to ``importlib.metadata``, it emits
one :class:`MgfPytestPluginMissingWarning` per process. Projects that
run pytest with ``filterwarnings = ["error"]`` (the federation
default) therefore FAIL fast instead of silently degrading — which is
the point.

Deliberate silences (no warning):

- Not inside a pytest test (``PYTEST_CURRENT_TEST`` unset) — normal
  runtime imports cost one env lookup.
- The plugin module is loaded (entry point, ``pytest_plugins =
  ["mgf.common.pytest_plugin"]`` in conftest, or ``-p``).
- The entry point IS visible but the plugin isn't loaded — that's an
  explicit ``-p no:mgf_common`` opt-out; respected.
- ``MGF_COMMON_NO_PLUGIN_WARN=1`` — the documented kill switch for
  consumers who intentionally run without the plugin under editable
  installs.

The fix the warning points at is the PAPER-23 documented opt-in::

    # tests/conftest.py
    pytest_plugins = ["mgf.common.pytest_plugin"]
"""

from __future__ import annotations

import os
import sys
import warnings

_PLUGIN_MODULE = "mgf.common.pytest_plugin"
_KILL_SWITCH = "MGF_COMMON_NO_PLUGIN_WARN"

# One warning per process; also latched by the deliberate-silence
# outcomes so the metadata scan runs at most once per process.
_probed = False


class MgfPytestPluginMissingWarning(UserWarning):
    """``mgf.common`` is importable inside a pytest run, but its
    ``pytest11`` plugin never loaded and no entry point is visible —
    the PAPER-23 editable-install silence."""


def warn_if_plugin_silently_absent() -> None:
    """Emit the PAPER-23 warning when the plugin silence applies.

    Called from ``mgf.common.__init__`` (covers app code importing
    mgf.common mid-test) and from ``bootstrap_for_test`` (covers the
    canonical test-helper path even when the import happened before
    pytest started). Cheap and side-effect-free outside pytest.
    """
    global _probed
    if _probed:
        return
    if "PYTEST_CURRENT_TEST" not in os.environ:
        # Not inside a live pytest test — do NOT latch; a later
        # in-test call (bootstrap_for_test) still gets to probe.
        return
    _probed = True
    if os.environ.get(_KILL_SWITCH):
        return
    if _PLUGIN_MODULE in sys.modules:
        return  # loaded — entry point, conftest pytest_plugins, or -p
    if _entry_point_visible():
        return  # registered but unloaded = explicit -p no:mgf_common
    warnings.warn(
        "mgf-common is importable but its pytest plugin never loaded and "
        "no `pytest11` entry point is visible (the PAPER-23 editable-"
        "install silence): mgf_* fixtures are unavailable and "
        "--mgf-perf / MGF_PERF capture will silently no-op. Fix: add\n"
        '    pytest_plugins = ["mgf.common.pytest_plugin"]\n'
        "to your top-level tests/conftest.py (survives `uv sync`), or "
        "install mgf-common as a wheel. Intentional? Set "
        f"{_KILL_SWITCH}=1 to silence this warning.",
        MgfPytestPluginMissingWarning,
        stacklevel=3,
    )


def _entry_point_visible() -> bool:
    """True when a pytest11 entry point targeting mgf.common exists."""
    try:
        from importlib import metadata

        eps = metadata.entry_points(group="pytest11")
        return any(ep.value.partition(":")[0].startswith("mgf.common") for ep in eps)
    except Exception:  # pragma: no cover - metadata backend quirks
        # Cannot tell — stay silent rather than risk a false positive.
        return True


__all__ = [
    "MgfPytestPluginMissingWarning",
    "warn_if_plugin_silently_absent",
]
