"""Smoke test — `mgf-test-supervisor --self-check` against itself.

Demonstrates eating-your-own-dogfood. If the supervisor can't pass
its own self-check, no claim it makes about consumer test runs is
trustworthy.

This test runs the CLI in subprocess (so we don't poison the
current pytest's state) and asserts exit 0 + "PASS" in stdout.

Marked @pytest.mark.e2e: it drives the full supervisor end-to-end
(real pytest subprocesses through the pass/fail/hang/crash canned
scenarios, ~32s) — tier-3 by budget, excluded from the fast
bare-pytest default and run by the dedicated e2e CI step. (It
historically carried smoke+slow; `slow` completed its deprecation
cycle in M2 Wave-2, and a ~32s test was never honest tier-0 smoke.)
"""

from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path

import pytest

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


@pytest.mark.e2e  # ~32s end-to-end self-check — excluded from the fast bare-pytest default; runs in the e2e-suite CI step + via `mtest --tier 3` / `--tier 0-3`
@pytest.mark.timeout(120)
def test_self_check_passes_on_own_project() -> None:
    """Run `mgf-test-supervisor --self-check` from this project's
    root and assert it reports PASS.

    Note: this test takes ~35s because the hang scenario waits for
    a per-test timeout. @pytest.mark.timeout(120) gives us 4x
    headroom over the supervisor's own ~30s expected ceiling."""
    env = os.environ.copy()
    env["MGF_TEST_SUPERVISOR_REPO_ROOT"] = str(REPO_ROOT)
    proc = subprocess.run(
        [sys.executable, "-m", "mgf.test_supervisor", "--self-check"],
        cwd=REPO_ROOT,
        env=env,
        capture_output=True,
        text=True,
        timeout=90,
        check=False,
    )
    combined = proc.stdout + proc.stderr
    assert proc.returncode == 0, (
        f"--self-check exited {proc.returncode} (expected 0)\n"
        f"--- stdout ---\n{proc.stdout}\n"
        f"--- stderr ---\n{proc.stderr}\n"
    )
    assert "[mtest --self-check] PASS" in combined, f"--self-check did not report PASS:\n{combined}"
