"""Real MCP transport tests. Run with the same Python used to install requirements."""
import asyncio
import sys
from pathlib import Path
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def main():
    params = StdioServerParameters(command=sys.executable,
        args=[str(Path(__file__).with_name("resource_server.py"))])
    checks = 0
    async with stdio_client(params) as (read, write):
        async with ClientSession(read, write) as client:
            await client.initialize()
            found = await client.list_tools()
            assert [t.name for t in found.tools] == ["find_resources"]
            assert found.tools[0].annotations.readOnlyHint
            assert set(found.tools[0].inputSchema["properties"]) == {"topic", "max_minutes"}
            checks += 3
            cases = [
                ({"topic": "Python"}, ["py-loops", "py-functions"]),
                ({"topic": " PYTHON ", "max_minutes": 20}, ["py-loops"]),
                ({"topic": "MCP", "max_minutes": 30}, []),
                ({"topic": "MCP", "max_minutes": 40}, ["mcp-contracts"]),
                ({"topic": "gardening"}, []),
            ]
            for args, ids in cases:
                result = await client.call_tool("find_resources", args)
                assert not result.isError, args
                data = result.structuredContent
                assert data["demo"] is True
                assert [x["id"] for x in data["resources"]] == ids
                assert data["count"] == len(ids)
                checks += 1
            invalid = [{}, {"topic": " "}, {"topic": "x"*81}, {"topic": ["Python"]},
                       {"topic": "Python", "max_minutes": 0},
                       {"topic": "Python", "max_minutes": 121},
                       {"topic": "Python", "max_minutes": True},
                       {"topic": "Python", "max_minutes": "20"}]
            for args in invalid:
                result = await client.call_tool("find_resources", args)
                assert result.isError, args
                checks += 1
    print(f"PASS: {checks} discovery, schema, result and validation cases")

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