"""Tests for Clarity value serialization."""

from x402_stacks.stacks_tx.clarity import (
    serialize_uint,
    serialize_standard_principal,
    serialize_optional_none,
    serialize_optional_some,
    serialize_buffer,
    serialize_buffer_from_string,
)
from x402_stacks.stacks_tx.constants import (
    CLARITY_TYPE_UINT,
    CLARITY_TYPE_STANDARD_PRINCIPAL,
    CLARITY_TYPE_OPTIONAL_NONE,
    CLARITY_TYPE_OPTIONAL_SOME,
    CLARITY_TYPE_BUFFER,
)


class TestSerializeUint:
    def test_zero(self):
        result = serialize_uint(0)
        assert result[0] == CLARITY_TYPE_UINT
        assert len(result) == 17  # 1 type + 16 value
        assert result[1:] == b"\x00" * 16

    def test_one(self):
        result = serialize_uint(1)
        assert result[0] == CLARITY_TYPE_UINT
        assert result[-1] == 1
        assert result[1:-1] == b"\x00" * 15

    def test_large_value(self):
        result = serialize_uint(1_000_000)
        assert result[0] == CLARITY_TYPE_UINT
        assert int.from_bytes(result[1:], "big") == 1_000_000


class TestSerializePrincipal:
    def test_type_prefix(self):
        # Use a known testnet address
        from x402_stacks.stacks_tx.keys import private_key_to_address
        addr = private_key_to_address(
            "edf9aee84d9b7abc145504dde6726c64f369d37ee34ced614f76c2dcb7004497",
            "testnet"
        )
        result = serialize_standard_principal(addr)
        assert result[0] == CLARITY_TYPE_STANDARD_PRINCIPAL
        assert len(result) == 22  # 1 type + 1 version + 20 hash


class TestSerializeOptional:
    def test_none(self):
        result = serialize_optional_none()
        assert result == bytes([CLARITY_TYPE_OPTIONAL_NONE])

    def test_some(self):
        inner = serialize_uint(42)
        result = serialize_optional_some(inner)
        assert result[0] == CLARITY_TYPE_OPTIONAL_SOME
        assert result[1:] == inner


class TestSerializeBuffer:
    def test_empty(self):
        result = serialize_buffer(b"")
        assert result[0] == CLARITY_TYPE_BUFFER
        assert result[1:5] == b"\x00\x00\x00\x00"
        assert len(result) == 5

    def test_data(self):
        data = b"hello"
        result = serialize_buffer(data)
        assert result[0] == CLARITY_TYPE_BUFFER
        length = int.from_bytes(result[1:5], "big")
        assert length == 5
        assert result[5:] == data

    def test_from_string(self):
        result = serialize_buffer_from_string("hello")
        assert result[0] == CLARITY_TYPE_BUFFER
        length = int.from_bytes(result[1:5], "big")
        assert length == 5
        assert result[5:] == b"hello"
