"""PAPER-08 end-to-end — feed the supervisor a real failing test and
assert the node-id AND the assertion detail land on stdout.

The unit pins (tests/unit/test_print_failures.py) drive the printer with
synthetic records. This one drives the REAL path: a real consumer
project, a real chunked pytest subprocess, real JUnit-XML parsing — the
same route mgf-hrb's red CI takes — and asserts the pipeline log is
self-sufficient.
"""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING

import pytest

from mgf.test_supervisor.supervisor import RunConfig, Supervisor

if TYPE_CHECKING:
    from pathlib import Path

_SUITE = """\
def test_ok():
    assert True


def test_red():
    expected = 4
    assert 2 + 2 == expected + 1, "arithmetic betrayed us"
"""

ID_OK = "tests/test_print_suite.py::test_ok"
ID_RED = "tests/test_print_suite.py::test_red"


def _write_consumer_project(root: Path) -> None:
    (root / "pyproject.toml").write_text("[tool.pytest.ini_options]\n", encoding="utf-8")
    tests_dir = root / "tests"
    tests_dir.mkdir()
    (tests_dir / "test_print_suite.py").write_text(_SUITE, encoding="utf-8")


@pytest.mark.integration
@pytest.mark.regression
@pytest.mark.timeout(120)
def test_failing_test_detail_reaches_stdout(
    tmp_path: Path, capfd: pytest.CaptureFixture[str]
) -> None:
    _write_consumer_project(tmp_path)
    cfg = RunConfig(
        repo_root=tmp_path,
        gates_dir=tmp_path / ".gates",
        test_ids=[ID_OK, ID_RED],
        test_markers={},
        run_id="run-print-e2e",
        pytest_cmd=[sys.executable, "-m", "pytest"],
        print_failures="always",
    )
    rc = Supervisor(cfg).run()
    assert rc == 1
    out = capfd.readouterr().out

    # The one-liner still says THAT it is red …
    assert "[mtest] FAIL:" in out
    # … and now the log also says WHICH test and WHY.
    assert ID_RED in out
    assert "arithmetic betrayed us" in out
    assert "failures/tests_test_print_suite.py__test_red.txt" in out
    # The green test is not dragged into the failure section.
    assert f"FAILED: {ID_OK}" not in out
