"""HTTP integration tests for the FastAPI + A2A mounting helpers."""

from __future__ import annotations

import uuid
from collections.abc import AsyncIterator
from typing import Any

import httpx
import pytest
from a2a.types import (
    Message,
    MessageSendParams,
    Part,
    Role,
    SendMessageRequest,
    TextPart,
)
from fastapi import FastAPI
from langchain_core.messages import AIMessage
from langgraph.graph import END, START, MessagesState, StateGraph

from a2a_langgraph.fastapi import add_langgraph_fastapi_endpoint


def _echo_graph() -> Any:
    def chatbot(state: MessagesState) -> dict[str, Any]:
        last = state["messages"][-1]
        text = getattr(last, "content", str(last))
        return {"messages": [AIMessage(content=f"echo:{text}")]}

    builder = StateGraph(MessagesState)
    builder.add_node("chatbot", chatbot)
    builder.add_edge(START, "chatbot")
    builder.add_edge("chatbot", END)
    return builder.compile()


@pytest.fixture
async def a2a_app() -> AsyncIterator[FastAPI]:
    app = FastAPI()
    add_langgraph_fastapi_endpoint(
        app,
        graph=_echo_graph(),
        mount_path="/agent",
        base_url="http://test",
        agent_name="Test Agent",
        agent_description="Integration test",
    )
    yield app


@pytest.mark.asyncio
async def test_agent_card(a2a_app: FastAPI) -> None:
    transport = httpx.ASGITransport(app=a2a_app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        r = await client.get("/agent/.well-known/agent-card.json")
    assert r.status_code == 200
    data = r.json()
    assert data["name"] == "Test Agent"
    assert data["url"] == "http://test/agent"


@pytest.mark.asyncio
async def test_message_send(a2a_app: FastAPI) -> None:
    msg = Message(
        message_id=str(uuid.uuid4()),
        role=Role.user,
        parts=[Part(root=TextPart(text="hello"))],
    )
    body = SendMessageRequest(
        id="req-1",
        params=MessageSendParams(message=msg),
    ).model_dump(mode="json", exclude_none=True)

    transport = httpx.ASGITransport(app=a2a_app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        r = await client.post("/agent/", json=body)

    assert r.status_code == 200
    payload = r.json()
    assert payload.get("jsonrpc") == "2.0"
    assert "result" in payload
    result = payload["result"]
    assert isinstance(result, dict)
    parts = result.get("parts") or []
    texts: list[str] = []
    for part in parts:
        root = part.get("root") if isinstance(part, dict) else None
        block = root if isinstance(root, dict) else part
        if isinstance(block, dict) and block.get("kind") == "text":
            texts.append(str(block.get("text", "")))
    joined = " ".join(texts)
    assert "echo:hello" in joined
