import json

import pytest

from a2a_agent.protocol import AgentCard
from a2a_agent.protocol import Message
from a2a_agent.protocol import PairingReply
from a2a_agent.protocol import PairingRequest
from a2a_agent.protocol import Task


def test_task_round_trip_maps_from_key() -> None:
    task = Task(
        id="task-001",
        from_="commander",
        to="device-b",
        status="pending",
        messages=[
            Message(
                role="user",
                parts=[{"type": "text", "text": "check project"}],
            )
        ],
    )

    payload = task.to_json()
    raw = json.loads(payload)

    assert raw["from"] == "commander"
    assert "from_" not in raw
    assert Task.from_json(payload) == task


def test_agent_card_round_trip() -> None:
    card = AgentCard(name="Device B")

    assert AgentCard.from_json(card.to_json()) == card


def test_pairing_messages_round_trip() -> None:
    request = PairingRequest(code="ABC234")
    reply = PairingReply(
        ok=True,
        room="team",
        device_name="device-b",
        token="token",
        broker={"host": "broker.example.com", "port": 1883, "tls": False},
    )

    assert PairingRequest.from_json(request.to_json()) == request
    assert PairingReply.from_json(reply.to_json()) == reply


def test_task_rejects_unknown_status() -> None:
    with pytest.raises(ValueError):
        Task(
            id="task-001",
            from_="commander",
            to="device-b",
            status="unknown",
            messages=[],
        )
