import asyncio
from datetime import timedelta
from pathlib import Path
import sys

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

from library_mcp import GUIDE_URI


def library_server():
    return StdioServerParameters(
        command=sys.executable,
        args=[str(Path(__file__).with_name("library_mcp.py").resolve())],
    )


async def main():
    async with stdio_client(library_server()) as (read, write):
        async with ClientSession(read, write, read_timeout_seconds=timedelta(seconds=15)) as session:
            await session.initialize()
            tools = await session.list_tools()
            resources = await session.list_resources()
            print("Tools:", ", ".join(tool.name for tool in tools.tools))
            print("Resources:", ", ".join(str(item.uri) for item in resources.resources))
            guide = await session.read_resource(GUIDE_URI)
            print("Visiting guide:", guide.contents[0].text)

            result = await session.call_tool("lookup_hours", {"branch": "central"})
            if result.isError or result.structuredContent is None:
                raise ValueError("The server could not return the branch hours.")
            print("Central hours:", result.structuredContent["hours"])

            invalid = await session.call_tool("lookup_hours", {"branch": "north"})
            if not invalid.isError:
                raise ValueError("Expected the server to reject an unknown branch.")
            print("Unknown branch rejected.")


if __name__ == "__main__":
    asyncio.run(main())
