"""R-T1-9E (survivability §3.7, Tier-1 #9, S5) — bounded enumeration
results.

`dump_all` / `inspect_full` already emit an honest `truncated` flag. The
`list` and `list_leases` formatters did NOT: on a full response buffer
they silently dropped records (dishonest) and the fixed `]}\\n` suffix
write could run past the buffer when results filled it exactly (a latent
crash). Both now reserve a tail margin, stop emitting before it, and emit
`"truncated":<bool>` — the consumer's signal to re-issue against a
narrower scope.

These pins assert the field is now present and back-compatible. Driving
an actual truncation needs >64 KiB of URNs (the fake test backend
exposes only a couple), so the overflow-safety + truncation honesty ride
on the reserved-margin code path; here we pin the wire-additive field on
the common (fits) case.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

import pytest

from tests.contract.conftest import rt

if TYPE_CHECKING:
    import socket

pytestmark = pytest.mark.contract


def test_list_carries_truncated_flag(
    raw_broker_with_cap: tuple[socket.socket, int],
) -> None:
    """`list` now emits a top-level `truncated` boolean; on a normal host
    everything fits, so it's False — and `resources` is still present and
    a list (back-compat: the SDK reads `resources` and ignores the rest)."""
    sock, _cap = raw_broker_with_cap
    resp = rt(sock, {"op": "list", "scope": "hw:/**"})
    assert resp.get("ok") is True
    assert isinstance(resp.get("resources"), list), "resources stays present + a list"
    assert resp.get("truncated") is False, (
        f"a fitting list must report truncated=false, not {resp.get('truncated')!r}"
    )


def test_list_leases_carries_truncated_flag(
    raw_broker_with_cap: tuple[socket.socket, int],
) -> None:
    """`list_leases` likewise emits `truncated`; empty/fitting → False,
    `leases` stays present + a list."""
    sock, cap_id = raw_broker_with_cap
    resp = rt(sock, {"op": "list_leases", "scope": "hw:/**", "cap_id": cap_id})
    assert resp.get("ok") is True
    assert isinstance(resp.get("leases"), list)
    assert resp.get("truncated") is False
