"""Use case: bulk-introspect every URN in a scope in one round-trip.

Cites: `hrb-design/mgf-hrb-self-aware-introspection.md` §5.5.3
(Part 13 — Self-Aware Hardware Introspection). The motivating
scenario from the 2026-05-26 design review was "max data gathering —
ability to dump and view all info across all the hardware chain."

The scenario in words:

  1. A GUI or diagnostic consumer wants every device's full inspect
     record in one call — e.g., the "initial-render" path of a
     hardware-tree pane, or the "snapshot for support" pane.
  2. The consumer calls `Client.dump_all("hw:/usb/**")` (or `"hw:/**"`
     for everything).
  3. Receives a typed `DumpAllResult` carrying the ordered list of
     `ResourceDetail` records — same shape `Client.inspect()` returns,
     just plural — plus a `truncated` flag that's True when the
     scope matched more than the response buffer could fit.

What we pin (verified against the broker on this host):

  * Synthetic scope (`hw:/test/**`) returns exactly the 2 seeded fakes.
  * USB scope returns the live count + each item carries the
    Part 13 §5.2.1 `driver` / `module` attrs when bound.
  * The fake backend honestly emits no `driver` attr (G2).
  * Empty scope returns `count: 0`, `items: ()`, `truncated: False`.
  * `truncated` stays False on this host's hardware count (~50 URNs)
    against the 64 KB response buffer.
"""

from __future__ import annotations

import pytest

from mgf.hrb import Client, DumpAllResult, ResourceDetail

pytestmark = [pytest.mark.use_case, pytest.mark.timeout(60)]


def test_dump_all_fake_scope_returns_all_seeded(broker: Client) -> None:
    """The synthetic `hw:/test/` worker seeds exactly 3 URNs
    (dev0 + dev1 + the G6 adversarial-attr fixture edge_attrs —
    see hrb-code/src/server.zig). dump_all on that scope MUST
    return them; honest emptiness for any out-of-scope URNs."""
    result = broker.dump_all("hw:/test/**")
    assert isinstance(result, DumpAllResult)
    assert result.scope == "hw:/test/**"
    assert result.count == 3
    assert result.truncated is False
    urns = {item.urn for item in result.items}
    assert urns == {"hw:/test/dev0", "hw:/test/dev1", "hw:/test/edge_attrs"}


def test_dump_all_items_are_typed_resource_detail(broker: Client) -> None:
    """Every item is a typed `ResourceDetail` (not a raw dict).
    Pin so a future SDK refactor can't accidentally regress to
    the wire shape — consumers depend on the typed projection."""
    result = broker.dump_all("hw:/test/**")
    assert all(isinstance(item, ResourceDetail) for item in result.items)
    for item in result.items:
        assert item.urn.startswith("hw:/test/")
        assert item.kind  # non-empty enum value


def test_dump_all_empty_scope_returns_empty(broker: Client) -> None:
    """G2 honest emptiness: a scope matching no URNs MUST return
    `count: 0`, `items: ()`, `truncated: False`. No silent fallback
    to "everything"; no error."""
    result = broker.dump_all("hw:/nonexistent/**")
    assert result.count == 0
    assert result.items == ()
    assert result.truncated is False
    assert result.scope == "hw:/nonexistent/**"


def test_dump_all_carries_driver_attrs_when_present(broker: Client) -> None:
    """The dump_all items carry the same attrs as a per-URN
    inspect — including the Part 13 §5.2.1 `driver` / `module`
    attrs when a kernel driver is bound. Pin against the USB
    scope; skip honestly when this host has no USB interfaces
    (rare but possible in a stripped CI container).
    """
    result = broker.dump_all("hw:/usb/**")
    if result.count == 0:
        pytest.skip("no USB interfaces on this host")

    found_one_with_driver = False
    for item in result.items:
        attrs = dict(item.attrs)
        if "driver" in attrs:
            found_one_with_driver = True
            assert isinstance(attrs["driver"], str)
            assert len(attrs["driver"]) > 0
            break
    assert found_one_with_driver, (
        f"none of {result.count} USB interfaces reported a driver attr — "
        "either the host is pathological or sub-phase 1A regressed"
    )


def test_dump_all_full_hardware_fits_under_buffer(broker: Client) -> None:
    """On a real host, dump_all('hw:/**') returns every URN the
    broker knows about (PCI + USB + test). On this developer
    machine that's ~50 URNs; the 64 KB response buffer comfortably
    fits the assembled response. Pin truncated=False so a future
    accidental shrink of the buffer surfaces here."""
    result = broker.dump_all("hw:/**")
    # The fake backend always contributes 2; PCI + USB contribute
    # the host-specific count. At minimum we expect 2.
    assert result.count >= 2
    assert result.truncated is False, (
        f"dump_all('hw:/**') truncated at {result.count} items — "
        "either the host has an unusually large device count, or "
        "the broker's response buffer regressed below 64 KB"
    )
