"""Regression pins for plugin-flag hygiene in the supervisor.

The supervisor invokes `pytest` as a subprocess. The flags it passes
MUST work whether or not optional pytest plugins (pytest-cov,
pytest-django, etc.) are installed in the consumer's environment.

History — why this file exists:

* **L6 (2026-05-26, mgf-apiprobe sibling-#7 adoption — pre-extraction).**
  The supervisor previously passed `--no-cov` to disable coverage
  measurement during the supervisor's own `--collect-only` and
  per-chunk runs. `--no-cov` is a **pytest-cov-specific** flag —
  pytest rejects it as unknown when pytest-cov isn't installed.
  mgf-apiprobe uses bare `coverage` and doesn't install pytest-cov.
  Result: every `--self-check` scenario failed with "(collection
  returned no tests)" — opaque to the adopter, only diagnosable by
  manual pytest re-run.

  Fix: replaced `--no-cov` with `-p no:pytest_cov` — pytest's
  standard "disable plugin if loaded; silent no-op if not" pattern.
  Works regardless of whether pytest-cov is installed.

If any test below fails, you reintroduced a plugin-specific flag.
Use `-p no:<plugin_name>` instead (the canonical disable-if-loaded
pattern).
"""

from __future__ import annotations

import sys
from pathlib import Path

from mgf.test_supervisor import supervisor


class TestPytestCovFlagBanned:
    def _supervisor_source(self) -> str:
        return Path(supervisor.__file__).read_text()

    def test_supervisor_never_passes_no_cov(self) -> None:
        source = self._supervisor_source()
        for i, line in enumerate(source.splitlines(), start=1):
            stripped = line.split("#", 1)[0]
            if '"--no-cov"' in stripped or "'--no-cov'" in stripped:
                raise AssertionError(
                    f"L6 regression — `--no-cov` reintroduced at "
                    f'supervisor.py:{i}. Use `"-p", "no:pytest_cov"` '
                    f"instead (the canonical disable-plugin pattern; "
                    f"works whether pytest-cov is installed or not).\n"
                    f"    line: {line.rstrip()}"
                )

    def test_supervisor_uses_p_no_plugin_pattern(self) -> None:
        source = self._supervisor_source()
        assert '"no:pytest_cov"' in source, (
            "Supervisor no longer disables pytest-cov on its own "
            "subprocess invocations. Per-chunk coverage measurement "
            "would double CI time + confuse output. Reinstate "
            "`-p no:pytest_cov` in supervisor's pytest subprocess "
            "arglists."
        )

    def test_supervisor_uses_cacheprovider_disable(self) -> None:
        source = self._supervisor_source()
        assert '"no:cacheprovider"' in source, (
            "Supervisor no longer disables pytest's cacheprovider "
            "on its subprocess invocations. Without it, supervisor's "
            "internal pytest spawns will pollute the project's "
            "`.pytest_cache` with their own state."
        )


class TestCollectionFailureSurfaces:
    """L6 secondary lesson: `collect_tests()` returning [] was
    indistinguishable from "no tests collected." Fix: when collection
    returns [] AND pytest exited non-zero, print pytest's stderr."""

    def test_collect_tests_surfaces_stderr_on_failure(
        self,
        tmp_path: Path,
        capsys: object,
    ) -> None:
        bogus_cmd = [sys.executable, "-m", "pytest", "--definitely-not-a-flag"]
        result = supervisor.collect_tests(bogus_cmd, tmp_path)
        captured = capsys.readouterr()  # type: ignore[attr-defined]
        assert result == []
        assert "collection returned no tests" in captured.err, (
            "L6 regression — collect_tests returned [] silently. "
            "Got stderr:\n" + (captured.err or "<empty>")
        )
        assert "pytest stderr follows" in captured.err
