"""Smoke: the federation test supervisor (`mgf-test-supervisor`)
itself works in THIS project's environment.

The supervisor's whole reason to exist is to NOT lie about test
outcomes. If it can't tell a passing test from a failing one, none
of its other claims are trustworthy. This smoke test invokes
`mgf-test-supervisor --self-check` (the canned pass / fail / crash
/ hang scenarios) and fails if any scenario is misreported.

Marked `smoke` because it runs in the default suite — a broken
supervisor must surface immediately, not in some later opt-in run.

History: pre-2026-05-26 versions of this test invoked
`scripts/mtest --self-check` from this repo's in-tree copy of the
supervisor. Extraction to the published sibling
`mgf-test-supervisor` v0.1.0 retired the in-tree copy; this test
now invokes the installed CLI via `python -m mgf.test_supervisor`
(which works whether the console script is on PATH or not).

The check takes ~35 seconds because the hang scenario waits for
pytest-timeout to fire (which has a hard 30 s default + a few
seconds of overhead). The pytest-timeout for this test is
overridden to 90 s to accommodate.
"""

from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

import pytest

pytestmark = [pytest.mark.smoke, pytest.mark.timeout(90)]


_REPO_ROOT = Path(__file__).resolve().parents[2]


def test_mtest_self_check_passes() -> None:
    """`mgf-test-supervisor --self-check` must exit 0. The self-
    check runs four canned tests (pass, fail, crash, hang) and
    asserts each is classified correctly. A failure here means
    the supervisor itself is broken — any other test result the
    supervisor produces is suspect."""
    env = os.environ.copy()
    env["MGF_TEST_SUPERVISOR_REPO_ROOT"] = str(_REPO_ROOT)
    result = subprocess.run(
        [sys.executable, "-m", "mgf.test_supervisor", "--self-check"],
        cwd=str(_REPO_ROOT),
        env=env,
        capture_output=True,
        text=True,
        check=False,
        timeout=80,
    )
    assert result.returncode == 0, (
        f"mgf-test-supervisor --self-check failed "
        f"(exit {result.returncode}).\n"
        f"--- stdout ---\n{result.stdout}\n"
        f"--- stderr ---\n{result.stderr}"
    )
    # Defensive: the final line should report PASS — catches a
    # future regression where the supervisor exits 0 without
    # actually running the checks.
    assert "[mtest --self-check] PASS" in result.stdout, (
        f"--self-check exited 0 but did not print PASS:\n{result.stdout}"
    )
