"""CLI dispatch tests — every subcommand routes to its handler."""

from __future__ import annotations

import pytest

from mgf.fed.__main__ import main


def test_version_flag(capsys: pytest.CaptureFixture[str]) -> None:
    with pytest.raises(SystemExit) as exc:
        main(["--version"])
    assert exc.value.code == 0
    assert "mgf-fed" in capsys.readouterr().out


# Patch the SOURCE module of each handler (main() lazy-imports them after parse_args,
# so the dotted source path is what the `from ._x import run_x` binds — patching
# `__main__.run_x` would be shadowed by that re-import).
@pytest.mark.parametrize(
    ("argv", "target"),
    [
        (["status"], "mgf.fed._status.run_status"),
        (["drift-check"], "mgf.fed._drift.run_drift_check"),
        (["local-index"], "mgf.fed._index.run_local_index"),
        (["gates"], "mgf.fed._gates.run_gates"),
        (["local-ci", "mgf-http"], "mgf.fed._localci.run_local_ci"),
        (["release-local", "mgf-x"], "mgf.fed._release.release_local"),
        (["release-remote", "mgf-x"], "mgf.fed._release.release_remote"),
        (["scaffold", "mgf-x"], "mgf.fed._scaffold.run_scaffold"),
        (["registry"], "mgf.fed._registry.run_registry"),
    ],
)
def test_dispatch(monkeypatch: pytest.MonkeyPatch, argv: list[str], target: str) -> None:
    seen: dict[str, bool] = {}

    def _fake(*_a: object, **_k: object) -> int:
        seen["called"] = True
        return 0

    monkeypatch.setattr(target, _fake)
    assert main(argv) == 0
    assert seen.get("called") is True


def test_no_command_errors() -> None:
    with pytest.raises(SystemExit):
        main([])  # subparsers required=True → argparse exits non-zero
