import pytest
from clawid.core.payload import encode, decode, to_bits, from_bits, MAGIC


def test_encode_decode_roundtrip():
    metadata = {'uid': 'user123', 'platform': 'hawky.ai', 'ts': 1711234567}
    assert decode(encode(metadata)) == metadata


def test_magic_bytes_present():
    assert encode({'uid': 'x'})[:4] == MAGIC


def test_large_metadata_roundtrip():
    metadata = {
        'uid': 'user_abc123def456',
        'platform': 'hawky.ai',
        'ts': 1711234567,
        'asset_id': '550e8400-e29b-41d4-a716-446655440000',
        'model': 'stable-diffusion-xl',
        'prompt_hash': 'a3f9b2c1',
    }
    assert decode(encode(metadata)) == metadata


def test_invalid_magic_raises():
    bad = b'XXXX' + encode({'uid': 'x'})[4:]
    with pytest.raises(ValueError, match="magic"):
        decode(bad)


def test_corrupted_crc_raises():
    payload = bytearray(encode({'uid': 'x'}))
    payload[-1] ^= 0xFF  # flip last byte of CRC
    with pytest.raises(ValueError, match="CRC"):
        decode(bytes(payload))


def test_bits_roundtrip():
    data = b'hello clawID world!'
    assert from_bits(to_bits(data)) == data


def test_bits_length():
    data = b'abc'
    bits = to_bits(data)
    assert len(bits) == 24
    assert all(b in (0, 1) for b in bits)
