"""User-perspective tests for ``mgf.apiprobe.cli``.

Surfaces exercised:
  - :func:`main` returns 0 for ``--help`` and ``doctor``.
  - :func:`main` returns non-zero for an unknown subcommand.
  - The three ship-time subcommands (``run`` / ``checks`` /
    ``doctor``) are advertised in the help text.

The CLI catches argparse's ``SystemExit`` internally and returns
an int instead, so consumer code calling ``main()`` doesn't have
to wrap it in a try/except.
"""

from __future__ import annotations

import tarfile
from typing import TYPE_CHECKING

from mgf.apiprobe.cli import main

if TYPE_CHECKING:
    from pathlib import Path

    import pytest


class TestCli:
    def test_help_returns_zero(self) -> None:
        rc = main(["--help"])
        assert rc == 0

    def test_help_advertises_subcommands(
        self,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        main(["--help"])
        captured = capsys.readouterr()
        text = captured.out + captured.err
        for sub in ("run", "checks", "doctor"):
            assert sub in text, f"--help output does not advertise the {sub!r} subcommand"

    def test_doctor_returns_zero(self) -> None:
        # `doctor` is a self-check — runs without network and should
        # always pass on a healthy install.
        rc = main(["doctor"])
        assert rc == 0

    def test_unknown_subcommand_returns_nonzero(self) -> None:
        rc = main(["definitely-not-a-subcommand"])
        assert rc != 0

    def test_version_returns_zero_and_prints(
        self,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        # OP-01: rich --version. argparse's SystemExit is caught + translated to 0.
        rc = main(["--version"])
        assert rc == 0
        cap = capsys.readouterr()
        assert "apiprobe" in (cap.out + cap.err)

    def test_explain_returns_zero(
        self,
        capsys: pytest.CaptureFixture[str],
    ) -> None:
        # OP-05: inspect the effective configuration, secrets redacted.
        rc = main(["explain"])
        assert rc == 0
        assert "configuration" in capsys.readouterr().out

    def test_bundle_writes_tarball(self, tmp_path: Path) -> None:
        # OP-07: a single diagnostic artefact with system info + redacted config + doctor.
        dest = tmp_path / "bundle.tar.gz"
        rc = main(["bundle", "--out", str(dest)])
        assert rc == 0
        assert dest.is_file()
        with tarfile.open(dest) as tar:
            names = set(tar.getnames())
        assert {"system.json", "config.json", "doctor.txt"} <= names
