from aliro_harness.reader.tlv import find_top_level


def test_find_top_level_returns_value_bytes():
    # 86 41 [65B value]  9D 02 [2B value]
    blob = bytes([0x86, 0x41]) + b"\xaa" * 65 + bytes([0x9D, 0x02, 0xff, 0xee])
    assert find_top_level(blob, 0x86) == b"\xaa" * 65
    assert find_top_level(blob, 0x9D) == bytes([0xff, 0xee])
    assert find_top_level(blob, 0x42) is None


def test_short_form_length_under_128():
    value = b"\xbb" * 100
    blob = bytes([0x9E, 100]) + value
    assert find_top_level(blob, 0x9E) == value


def test_long_form_0x81_length_128_to_255():
    value = b"\xcc" * 200
    blob = bytes([0x9E, 0x81, 200]) + value
    assert find_top_level(blob, 0x9E) == value


def test_long_form_0x82_length_256_or_more():
    value = b"\xdd" * 1000
    blob = bytes([0x9E, 0x82, (1000 >> 8) & 0xFF, 1000 & 0xFF]) + value
    assert find_top_level(blob, 0x9E) == value


def test_returns_none_when_tag_absent():
    blob = bytes([0x86, 0x02, 0x01, 0x02, 0x9D, 0x01, 0x03])
    assert find_top_level(blob, 0x42) is None


def test_skips_over_unmatched_tags_to_find_later_match():
    # Three TLVs: 0x86, 0x9D, 0x9E. Ask for the third.
    tlv1 = bytes([0x86, 0x03, 0x11, 0x22, 0x33])
    tlv2 = bytes([0x9D, 0x02, 0x44, 0x55])
    tlv3 = bytes([0x9E, 0x04, 0x66, 0x77, 0x88, 0x99])
    blob = tlv1 + tlv2 + tlv3
    assert find_top_level(blob, 0x9E) == bytes([0x66, 0x77, 0x88, 0x99])


def test_zero_length_value_returns_empty_bytes():
    """Pin the 0-length contract — easy to break with a `if length > 0` micro-opt."""
    blob = bytes([0x86, 0x00, 0x9D, 0x02, 0x11, 0x22])
    assert find_top_level(blob, 0x86) == b""
    assert find_top_level(blob, 0x9D) == bytes([0x11, 0x22])


def test_empty_input_returns_none():
    assert find_top_level(b"", 0x9E) is None


def test_skips_long_form_unmatched_to_find_later_match():
    """Make sure the 0x82-length skip path advances correctly when the
    matched tag comes AFTER a long-form TLV (the current `skips_over_…`
    test only exercises short-form skips)."""
    skip_value = b"\x99" * 1000
    skip_tlv = bytes([0x86, 0x82, (1000 >> 8) & 0xFF, 1000 & 0xFF]) + skip_value
    target = bytes([0x9E, 0x02, 0xAB, 0xCD])
    assert find_top_level(skip_tlv + target, 0x9E) == bytes([0xAB, 0xCD])
