"""Integration: a real passing test driven end-to-end through mtest via the warden.

Stands up a tiny hermetic pytest project in a tmp dir (one trivial passing test),
then runs it through a real ``Warden`` wired to ``mtest_runner`` — exercising the
full path: Warden -> ``_mtest_child`` (a child process, because mtest installs
process-global signal handlers) -> ``Supervisor.run`` -> ``.gates/last-run/run.jsonl``
-> outcome mapping.

Why a hermetic tmp project (and not mgf-test-web's own suite): it is deterministic
and avoids any self-referential mtest-in-mtest coupling. A trivial top-level test
needs no project deps, so the supervisor's fallback ``pytest_cmd`` (this venv's
python) collects + runs it cleanly.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any

import pytest

from mgf.test_web.warden import RunRequest, Warden
from mgf.test_web.warden.runner import mtest_runner

_PYPROJECT = """\
[project]
name = "warden-itest-proj"
version = "0.0.0"
requires-python = ">=3.11"

[tool.pytest.ini_options]
minversion = "8.0"
"""

_TEST = """\
def test_ok() -> None:
    assert 1 + 1 == 2
"""


def _make_project(root: Path) -> str:
    """Write a minimal mtest-runnable project; return the single node-id."""
    (root / "pyproject.toml").write_text(_PYPROJECT, encoding="utf-8")
    (root / "conftest.py").write_text("# anchor pytest rootdir here\n", encoding="utf-8")
    (root / "test_smoke.py").write_text(_TEST, encoding="utf-8")
    return "test_smoke.py::test_ok"


@pytest.mark.integration
def test_mtest_runner_passes_a_real_test(tmp_path: Path) -> None:
    test_id = _make_project(tmp_path)
    events: list[dict[str, Any]] = []
    warden = Warden("itest", mtest_runner(tmp_path), on_event=events.append)

    outcome = warden.submit(RunRequest("r1", test_id))
    assert outcome.status == "started"
    assert warden.wait_idle(timeout=60), "warden did not go idle in time"

    # The end-to-end result: mtest ran the test, wrote run.jsonl, the adapter
    # mapped passed -> "pass".
    assert warden.result("r1") == "pass"

    # mtest actually wrote its JSONL log for this run.
    jsonl = tmp_path / ".gates" / "last-run" / "run.jsonl"
    assert jsonl.exists()

    # A test_end event was emitted carrying the mapped warden result.
    ends = [e for e in events if e.get("kind") == "test_end"]
    assert ends and ends[-1]["result"] == "pass"

    # And the adapter surfaced an `assert` event carrying mtest's raw outcome.
    asserts = [e for e in events if e.get("kind") == "assert"]
    assert asserts and asserts[-1]["outcome"] == "passed"
