"""
Simple test client for the selenium-mcp server.

Usage:
    poetry run python test_client.py
"""

import asyncio
import json
import sys

from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client

SERVER_URL = "http://localhost:8888/mcp"


async def main():
    async with streamable_http_client(SERVER_URL) as (r, w, _):
        async with ClientSession(r, w) as session:
            await session.initialize()

            # List available tools
            tools = await session.list_tools()
            print("Tools available:")
            for t in tools.tools:
                print(f"  - {t.name}")

            # Navigate to a page
            url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com"
            result = await session.call_tool(
                "selenium_navigate", {"params": {"url": url}}
            )
            nav = json.loads(result.content[0].text)
            sid = nav["session_id"]
            print(f"\nNavigated to: {nav['url']}")
            print(f"Title: {nav['title']}")
            print(f"Session ID: {sid}")

            # Get page text
            result = await session.call_tool(
                "selenium_get_page_content",
                {"params": {"session_id": sid, "content_type": "text"}},
            )
            content = json.loads(result.content[0].text)
            print(f"\nPage text:\n{content['text'][:500]}")

            # Get links
            result = await session.call_tool(
                "selenium_get_page_content",
                {"params": {"session_id": sid, "content_type": "links"}},
            )
            links = json.loads(result.content[0].text)
            print(f"\nLinks ({links['count']}):")
            for link in links["links"]:
                print(f"  {link['text']} -> {link['href']}")

            # Close browser session
            result = await session.call_tool(
                "selenium_close_session", {"params": {"session_id": sid}}
            )
            print(f"\n{result.content[0].text}")


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