"""Tests for c32check encoding/decoding."""

import pytest
from x402_stacks.stacks_tx.c32 import (
    c32_encode,
    c32_decode,
    c32_check_encode,
    c32_check_decode,
    c32_address,
    c32_address_decode,
)


class TestC32EncodeDecode:
    def test_roundtrip_basic(self):
        data = bytes.fromhex("deadbeef")
        encoded = c32_encode(data)
        decoded = c32_decode(encoded)
        assert decoded == data

    def test_roundtrip_zeros(self):
        data = b"\x00\x00\x01"
        encoded = c32_encode(data)
        decoded = c32_decode(encoded)
        assert decoded == data

    def test_empty(self):
        assert c32_encode(b"") == ""
        assert c32_decode("") == b""

    def test_single_byte(self):
        for i in range(256):
            data = bytes([i])
            assert c32_decode(c32_encode(data)) == data


class TestC32Check:
    def test_roundtrip(self):
        data = bytes(20)  # 20 zero bytes
        version = 22
        encoded = c32_check_encode(version, data)
        dec_version, dec_data = c32_check_decode(encoded)
        assert dec_version == version
        assert dec_data == data

    def test_invalid_checksum(self):
        data = bytes(20)
        encoded = c32_check_encode(22, data)
        # Corrupt last character
        corrupted = encoded[:-1] + ("1" if encoded[-1] != "1" else "2")
        with pytest.raises(ValueError, match="checksum"):
            c32_check_decode(corrupted)

    def test_version_range(self):
        data = bytes(20)
        for v in range(32):
            enc = c32_check_encode(v, data)
            dv, dd = c32_check_decode(enc)
            assert dv == v
            assert dd == data

        with pytest.raises(ValueError):
            c32_check_encode(32, data)


class TestC32Address:
    def test_mainnet_address_starts_with_sp(self):
        h160 = bytes.fromhex("0000000000000000000000000000000000000001")
        addr = c32_address(22, h160)
        assert addr.startswith("SP")

    def test_testnet_address_starts_with_st(self):
        h160 = bytes.fromhex("0000000000000000000000000000000000000001")
        addr = c32_address(26, h160)
        assert addr.startswith("ST")

    def test_roundtrip(self):
        h160 = bytes.fromhex("abcdef0123456789abcdef0123456789abcdef01")
        for version in (22, 26):
            addr = c32_address(version, h160)
            dec_ver, dec_hash = c32_address_decode(addr)
            assert dec_ver == version
            assert dec_hash == h160

    def test_invalid_no_s_prefix(self):
        with pytest.raises(ValueError, match="must start with"):
            c32_address_decode("T123")

    def test_invalid_hash160_length(self):
        with pytest.raises(ValueError, match="20 bytes"):
            c32_address(22, b"\x00" * 19)
