import asyncio
import sys
import pytest
from fastmcp import Client
from fastmcp.client.transports import StdioTransport
from fastmcp.exceptions import ToolError
from pydantic import ValidationError
from connected_book_tool import SERVER, book_chapter

def test_reads_the_known_chapter():
    answer = asyncio.run(book_chapter.ainvoke(
        {"title": "Python and Roots"}
    ))
    assert answer == "Python and Roots: 7 lessons"

def test_unknown_chapter_is_explicit():
    answer = asyncio.run(book_chapter.ainvoke(
        {"title": "Unknown chapter"}
    ))
    assert "Not found" in answer

def test_rejects_an_unexpected_path():
    with pytest.raises(ValidationError):
        asyncio.run(book_chapter.ainvoke({
            "title": "Python and Roots",
            "file_path": "private.txt",
        }))

def test_closes_the_client_after_a_failed_call():
    async def check_failure():
        transport = StdioTransport(
            command=sys.executable,
            args=[str(SERVER)],
        )
        client = Client(transport, timeout=5, init_timeout=10)
        with pytest.raises(ToolError):
            async with client:
                await client.call_tool("missing_tool", {})
        assert not client.is_connected()

    asyncio.run(check_failure())
