"""Child entry point for the mtest runner adapter (**D-MTEST-API**).

mgf-test-supervisor installs *process-global* ``SIGINT``/``SIGTERM`` handlers
that ``sys.exit`` (see ``Supervisor.__init__`` — it flushes state then exits
130/143). The warden is a long-lived, single-process broker that must outlive
its runners, so it MUST NOT drive the supervisor in its own process or thread:
one Ctrl-C aimed at a single run would tear the whole broker down. This module
is that isolation boundary — the warden spawns it as a fresh child process::

    python -m mgf.test_web.warden._mtest_child <project_root> <test_id>

It builds a single-test ``RunConfig`` (``test_ids=[test_id]``, ``chunk_size=1``
— the CLI cannot target one node-id, only the Python API can), runs
``Supervisor(...).run()`` (which writes ``<root>/.gates/last-run/run.jsonl``),
and exits with mtest's own exit code. The parent (``runner.mtest_runner``)
reads the per-test outcome back out of that JSONL — ``run()`` itself returns
only an aggregate exit code, not the record.

Kept deliberately tiny + import-light: it pulls in only the supervisor API.
"""

from __future__ import annotations

import sys
import time
from pathlib import Path

from mgf.test_supervisor.supervisor import RunConfig, Supervisor

# The project-interpreter preference (its own ``.venv``, mirroring mtest's
# ``_find_pytest_cmd``) lives in one place now — shared with ``testctl catalog``
# so the catalog enumerates with the exact interpreter a run here executes with.
from .._pyenv import pytest_cmd as project_pytest_cmd


def main(argv: list[str]) -> int:
    if len(argv) != 2:
        print(
            "usage: python -m mgf.test_web.warden._mtest_child <project_root> <test_id>",
            file=sys.stderr,
        )
        return 2
    root = Path(argv[0]).resolve()
    test_id = argv[1]
    cfg = RunConfig(
        repo_root=root,
        gates_dir=root / ".gates",
        test_ids=[test_id],
        test_markers={},
        run_id=f"warden-{int(time.time() * 1000)}",
        pytest_cmd=project_pytest_cmd(root),
        chunk_size=1,
    )
    # run() writes <root>/.gates/last-run/run.jsonl and returns an exit code
    # (0 all-passed, 1 some-failed, 2 supervisor-error). The warden reads the
    # per-test outcome from the JSONL, not this code — but we still propagate
    # it so the child's exit status is meaningful when run by hand.
    return Supervisor(cfg).run()


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
