"""CLI-level tests for ``aliro-bench-test``.

Mirrors ``test_personalizer_cli.py``. The pyscard import is lazy inside
``main()`` so most of these tests don't need pcscd at all. Tests that
exercise --list-readers monkeypatch ``smartcard.System.readers`` to keep
them hermetic.
"""

from click.testing import CliRunner

from aliro_harness.reader.cli import main


def test_help_lists_both_modes():
    result = CliRunner().invoke(main, ["--help"])
    assert result.exit_code == 0, result.output
    assert "--trust-dir" in result.output
    assert "--list-readers" in result.output


def test_bare_invocation_errors_with_clear_message_about_trust_dir():
    result = CliRunner().invoke(main, [])
    assert result.exit_code != 0
    assert "--trust-dir" in result.output
    # Click 8 prints "Error: ..." for UsageError; either wording is fine
    # so long as trust-dir is mentioned.


def test_list_readers_with_no_readers_exits_nonzero(monkeypatch):
    """If pcscd reports no readers, --list-readers prints a message + exits 1."""
    import smartcard.System

    monkeypatch.setattr(smartcard.System, "readers", lambda: [])
    result = CliRunner().invoke(main, ["--list-readers"])
    assert result.exit_code == 1
    # The message is printed to stderr; click.testing captures both into output.
    assert "No PC/SC readers found" in result.output


def test_list_readers_enumerates_each_with_index(monkeypatch):
    """Two fake readers should be printed with [0] / [1] prefixes."""
    import smartcard.System

    class FakeReader:
        def __init__(self, name: str) -> None:
            self._name = name

        def __str__(self) -> str:
            return self._name

    monkeypatch.setattr(
        smartcard.System,
        "readers",
        lambda: [FakeReader("ACS Reader 0"), FakeReader("ACS Reader 1")],
    )
    result = CliRunner().invoke(main, ["--list-readers"])
    assert result.exit_code == 0, result.output
    assert "[0] ACS Reader 0" in result.output
    assert "[1] ACS Reader 1" in result.output


def test_list_readers_does_not_require_trust_dir(monkeypatch):
    """The bug we're fixing: --list-readers should work standalone."""
    import smartcard.System

    monkeypatch.setattr(smartcard.System, "readers", lambda: [])
    result = CliRunner().invoke(main, ["--list-readers"])
    # Whatever the reader-discovery outcome, the failure mode must NOT be
    # Click's "Missing option '--trust-dir'" usage error.
    assert "Missing option" not in result.output
    assert "--trust-dir is required" not in result.output
