"""Pins for ``mgf-hrb explain <topic>``.

Each explainer carries a hardware-shape diagram + a vocabulary section
that maps the diagram terms 1:1 to the columns in the matching scan or
doctor output. These tests assert that vocabulary stays present: if the
scan output ever renames "Port-chain" → "PortPath", the explainer would
have to change too, and this test catches a silent drift.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from mgf.hrb.cli._explain import _TOPICS, explain_command

if TYPE_CHECKING:
    import pytest


# ---- topic listing ---------------------------------------------------------


def test_explain_no_topic_lists_available_topics(
    capsys: pytest.CaptureFixture[str],
) -> None:
    exit_code = explain_command(topic=None)
    assert exit_code == 0
    out = capsys.readouterr().out
    assert "mgf-hrb explain" in out
    # Every registered topic appears in the listing.
    for topic in _TOPICS:
        assert topic in out


def test_explain_empty_string_treated_as_list(
    capsys: pytest.CaptureFixture[str],
) -> None:
    exit_code = explain_command(topic="")
    assert exit_code == 0
    assert "Available topics" in capsys.readouterr().out


def test_explain_literal_list_keyword(capsys: pytest.CaptureFixture[str]) -> None:
    exit_code = explain_command(topic="list")
    assert exit_code == 0
    assert "Available topics" in capsys.readouterr().out


# ---- USB explainer ---------------------------------------------------------


def test_explain_usb_renders(capsys: pytest.CaptureFixture[str]) -> None:
    """The USB explainer must carry the exact column labels used in
    mgf-hrb-usb-scan output (Bus, Port-chain, If, VID:PID, Class, URN).
    Drift detection: rename a column in usb_scan.zig and this test fails."""
    exit_code = explain_command(topic="usb")
    assert exit_code == 0
    out = capsys.readouterr().out
    # Header.
    assert "USB" in out
    # Diagram landmarks.
    assert "Host Controller" in out
    assert "Root Hub" in out
    assert "interface" in out.lower()
    # Column labels — must match usb_scan.zig exactly.
    assert "Bus" in out
    assert "Port-chain" in out
    assert "VID:PID" in out
    assert "Class" in out
    assert "URN" in out
    # The worked example uses a real-looking URN.
    assert "hw:/usb/bus" in out


# ---- PCIe explainer --------------------------------------------------------


def test_explain_pci_renders(capsys: pytest.CaptureFixture[str]) -> None:
    """The PCI explainer covers BDF, IOMMU groups, VFIO — the vocabulary
    a reader will hit in scan/doctor output and in passthrough flows."""
    exit_code = explain_command(topic="pci")
    assert exit_code == 0
    out = capsys.readouterr().out
    assert "PCIe" in out
    assert "Root Complex" in out
    assert "BDF" in out
    assert "IOMMU" in out
    assert "VFIO" in out
    assert "hw:/pci/" in out


# ---- doctor explainer ------------------------------------------------------


def test_explain_doctor_renders(capsys: pytest.CaptureFixture[str]) -> None:
    """The doctor explainer must list every category the polished doctor
    renders, so a reader running `mgf-hrb doctor` can find each section
    explained here."""
    exit_code = explain_command(topic="doctor")
    assert exit_code == 0
    out = capsys.readouterr().out
    # Every doctor category gets coverage in the explainer.
    assert "Substrate" in out
    assert "Hardware policy" in out
    assert "Broker" in out
    # Every status code is documented.
    for status in ("OK", "WARN", "FAIL"):
        assert status in out


# ---- error path ------------------------------------------------------------


def test_explain_unknown_topic_returns_2_and_suggests(
    capsys: pytest.CaptureFixture[str],
) -> None:
    """An unknown topic gets a non-zero exit + a 'did you mean' hint when
    the typo is close to a real topic."""
    exit_code = explain_command(topic="ubs")  # transposed letters of "usb"
    assert exit_code == 2
    err = capsys.readouterr().err
    assert "unknown topic 'ubs'" in err
    assert "Did you mean" in err
    assert "usb" in err


def test_explain_unknown_topic_far_from_known_skips_suggestion(
    capsys: pytest.CaptureFixture[str],
) -> None:
    """When the typo is too far from any known topic, we skip the 'did you
    mean' block (no helpful suggestion would be made) but still list the
    available topics."""
    exit_code = explain_command(topic="zzzzzzzz")
    assert exit_code == 2
    err = capsys.readouterr().err
    assert "unknown topic 'zzzzzzzz'" in err
    assert "Available topics:" in err


def test_explain_case_insensitive(capsys: pytest.CaptureFixture[str]) -> None:
    """`mgf-hrb explain USB` and `mgf-hrb explain Usb` work the same."""
    for arg in ("USB", "Usb", "UsB"):
        exit_code = explain_command(topic=arg)
        assert exit_code == 0, f"failed for topic={arg!r}"
        capsys.readouterr()  # drain
