import base64

from meshy.smaz import _decompress, try_decode_prefixed


class TestDecompress:
    def test_codebook_lookup(self):
        result = _decompress(bytes([0]))
        assert result == b" "

    def test_codebook_the(self):
        result = _decompress(bytes([1]))
        assert result == b"the"

    def test_verbatim_single(self):
        result = _decompress(bytes([254, ord("X")]))
        assert result == b"X"

    def test_verbatim_run(self):
        result = _decompress(bytes([255, 2, ord("A"), ord("B"), ord("C")]))
        assert result == b"ABC"

    def test_mixed(self):
        result = _decompress(bytes([1, 0, 2]))
        assert result == b"the e"

    def test_empty(self):
        assert _decompress(b"") == b""


class TestTryDecodePrefixed:
    def test_no_prefix_returns_original(self):
        assert try_decode_prefixed("hello world") == "hello world"

    def test_plain_s_prefix_with_valid_smaz(self):
        compressed = bytes([1])  # "the"
        encoded = base64.b64encode(compressed).decode()
        result = try_decode_prefixed(f"s:{encoded}")
        assert result == "the"

    def test_non_base64_chars_stripped_by_lenient_decode(self):
        result = try_decode_prefixed("s:@@@")
        assert result == ""

    def test_url_safe_base64(self):
        compressed = bytes([254, ord("Z")])
        encoded = base64.urlsafe_b64encode(compressed).decode().rstrip("=")
        result = try_decode_prefixed(f"s:{encoded}")
        assert result == "Z"

    def test_empty_after_prefix_returns_original(self):
        assert try_decode_prefixed("s:") == "s:"
