from __future__ import annotations

import pytest

from mcp.server.fastmcp import FastMCP
from mrp.models import PollResult

from mrp_mcp.tools.threads import register


@pytest.fixture
def mcp_server(mock_agent, state):
    mcp = FastMCP("test")
    register(mcp, mock_agent, state)
    return mcp


@pytest.mark.asyncio
async def test_read_thread_empty(mcp_server, mock_agent):
    result = await mcp_server.call_tool("mrp_read_thread", {"thread_id": "thread-1"})
    text = result[0][0].text
    assert "No messages found" in text


@pytest.mark.asyncio
async def test_read_thread_with_messages(mcp_server, mock_agent, sample_messages):
    mock_agent.client.get_thread.return_value = PollResult(
        messages=sample_messages, next_cursor=None
    )

    result = await mcp_server.call_tool("mrp_read_thread", {"thread_id": "thread-1"})
    text = result[0][0].text

    assert "thread-1" in text
    assert "2 messages" in text
    assert "Hello there!" in text
    assert "How are you?" in text


@pytest.mark.asyncio
async def test_read_thread_with_pagination(mcp_server, mock_agent, sample_messages):
    mock_agent.client.get_thread.return_value = PollResult(
        messages=sample_messages, next_cursor="cursor-abc"
    )

    result = await mcp_server.call_tool("mrp_read_thread", {"thread_id": "thread-1"})
    text = result[0][0].text

    assert "More messages available" in text


@pytest.mark.asyncio
async def test_message_status(mcp_server, mock_agent):
    result = await mcp_server.call_tool(
        "mrp_message_status", {"message_id": "msg_001"}
    )
    text = result[0][0].text

    mock_agent.client.get_message_status.assert_called_once_with("msg_001")
    assert "msg_001" in text
    assert "delivered" in text.lower()
