"""Smoke: the `mgf-hrb` CLI runs at all.

The console-script entry point + argparse wiring would silently break
on a refactor (e.g., a removed subcommand, a stale module path). These
tests exercise the SHELL surface — what a user types — so a broken
entry-point fails CI fast, not at first-customer-install time.

Marker: `smoke`. ~50ms total; no broker subprocess required (the
"broker absent" cases are tested explicitly so the unhappy path
stays warm in CI).
"""

from __future__ import annotations

import subprocess
import sys

import pytest

pytestmark = pytest.mark.smoke


def _run_cli(*args: str, timeout: float = 5.0) -> subprocess.CompletedProcess[str]:
    """Invoke `python -m mgf.hrb.cli` with the given args. Uses
    `python -m` (not the `mgf-hrb` console script) so the test works
    from any CWD without depending on the venv's bin/ being on PATH.
    """
    return subprocess.run(  # noqa: S603 — argv form, trusted path
        [sys.executable, "-m", "mgf.hrb.cli", *args],
        capture_output=True,
        text=True,
        timeout=timeout,
    )


def test_cli_help_exits_zero() -> None:
    """`mgf-hrb --help` is the contract a new user sees first. If
    argparse is broken or a subcommand decl is malformed, this exits
    non-zero. Pinning at the smoke level catches the regression
    before a user does."""
    result = _run_cli("--help")
    assert result.returncode == 0, f"--help exited {result.returncode}; stderr:\n{result.stderr}"
    # The help output should mention each top-level subcommand —
    # catches a renamed/removed subcommand silently breaking the
    # documented surface.
    for subcmd in ("scan", "info", "doctor", "explain"):
        assert subcmd in result.stdout, f"`{subcmd}` missing from --help output:\n{result.stdout}"


def test_cli_doctor_against_missing_broker_exits_fail_with_remediation() -> None:
    """Without a broker, `doctor` must report the missing socket as
    FAIL and exit non-zero (the operator needs to KNOW the broker
    isn't up). The remediation text in the doctor's output is the
    UX contract — if we silently lose it, operator triage breaks."""
    result = _run_cli(
        "--socket",
        "/tmp/mgf-hrb-definitely-not-here.sock",
        "doctor",
        timeout=10.0,
    )
    # Exit code is 1 (FAIL) — broker socket missing is a hard fail
    # per the diagnostics engine's severity model.
    assert result.returncode == 1, (
        f"expected exit 1 for missing broker, got {result.returncode}\n"
        f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}"
    )
    # The output must surface the remediation.
    out = result.stdout + result.stderr
    assert "mgf-hrb-server" in out, f"remediation text missing; output:\n{out}"


def test_cli_explain_doctor_renders() -> None:
    """`mgf-hrb explain doctor` is the operator-facing reference for
    what each diagnostic check probes. Pinning ensures the topic
    table + renderer don't silently break."""
    result = _run_cli("explain", "doctor")
    assert result.returncode == 0
    # The explain output should mention key terms from the
    # diagnostics engine (SOCKET_REACHABLE, IOMMU, sysfs).
    assert "socket" in result.stdout.lower()
    assert "iommu" in result.stdout.lower()


def test_cli_unknown_subcommand_exits_with_argparse_error() -> None:
    """An unknown subcommand should fail with argparse's standard
    error path — not crash with a traceback. Pin so a future
    refactor that bypasses argparse doesn't lose this UX."""
    result = _run_cli("definitely-not-a-real-subcommand")
    assert result.returncode != 0
    # No Python traceback in the user-facing output.
    assert "Traceback" not in result.stderr
