from p2p.protocol.codec import decode, encode
from p2p.protocol.envelope import A2AEnvelope
from p2p.protocol.types import HelloPayload, MessageType, PAYLOAD_MODELS, TextPayload


class TestCodec:
    def test_text(self):
        e = A2AEnvelope(type=MessageType.TEXT, payload=TextPayload(text="hi").model_dump())
        d = decode(encode(e))
        assert d.payload["text"] == "hi"

    def test_hello(self):
        h = HelloPayload(agent_name="J", capabilities=["cal"])
        d = decode(encode(A2AEnvelope(type=MessageType.HELLO, payload=h.model_dump())))
        assert HelloPayload.model_validate(d.payload).agent_name == "J"

    def test_ping(self):
        d = decode(encode(A2AEnvelope(type=MessageType.PING)))
        assert d.type == MessageType.PING

    def test_reply(self):
        d = decode(encode(A2AEnvelope(type=MessageType.ACK, in_reply_to="x")))
        assert d.in_reply_to == "x"

    def test_all_types(self):
        for t in MessageType:
            assert t in PAYLOAD_MODELS

    def test_oversized_rejected(self):
        import pytest
        from p2p.errors import ProtocolError
        big = b"\x00" * (11 * 1024 * 1024)  # 11 MB
        with pytest.raises(ProtocolError, match="too large"):
            decode(big, max_size=10 * 1024 * 1024)

    def test_hello_has_ed25519_field(self):
        h = HelloPayload(agent_name="X", ed25519_pubkey_hex="aa" * 32)
        assert h.ed25519_pubkey_hex == "aa" * 32
