import json

from target_simulator.core.command_builder import build_json_reset_ids


def test_build_json_reset_ids_default():
    payloads = build_json_reset_ids()
    assert isinstance(payloads, list)
    assert len(payloads) > 0

    total_targets = 0
    ids = []
    for p in payloads:
        # payloads must be newline-terminated strings
        assert isinstance(p, str)
        assert p.endswith("\n")
        obj = json.loads(p)
        assert "TGTS" in obj
        tgts = obj["TGTS"]
        assert isinstance(tgts, list)
        for t in tgts:
            # ID should be present and within expected range
            assert "ID" in t
            ids.append(int(t["ID"]))
            # flags a (active) and t (traceable) must be zero for reset
            assert int(t.get("a", 0)) == 0
            assert int(t.get("t", 0)) == 0
            # Range (R) should be zero or 0.0
            assert float(t.get("R", 0)) == 0.0
        total_targets += len(tgts)

    # Default covers IDs 0..31 -> 32 targets
    assert total_targets == 32
    assert set(ids) == set(range(0, 32))


def test_build_json_reset_ids_respects_max_bytes_and_batching():
    # Use small max_bytes to force multiple batches for a small id range
    payloads = build_json_reset_ids(max_id=7, max_bytes=100)
    assert isinstance(payloads, list)
    assert len(payloads) >= 1

    total = 0
    for p in payloads:
        # Each returned payload should be parseable JSON and end with newline
        assert isinstance(p, str)
        assert p.endswith("\n")
        b = p.encode("utf-8")
        # Either it respects the provided max_bytes, or it's the single fallback
        assert len(b) <= 100 or len(payloads) == 1
        obj = json.loads(p)
        tgts = obj.get("TGTS", [])
        total += len(tgts)

    # We requested IDs 0..7 -> 8 targets total
    assert total == 8
