"""测试 Router Agent 的 HTTP 对话接口"""

import asyncio
import httpx
import sys

# 修复 Windows 控制台编码问题
if sys.platform == 'win32':
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
    sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')


async def test_chat_api():
    """测试 Router Agent 的对话接口"""
    base_url = "http://127.0.0.1:8001"

    print("=" * 60)
    print("Testing Router Agent Chat API")
    print("=" * 60)

    async with httpx.AsyncClient(timeout=60.0) as client:
        # 测试 1: 健康检查
        print("\n[Test 1] Health check...")
        try:
            response = await client.get(f"{base_url}/health")
            print(f"✓ Health: {response.json()}")
        except Exception as e:
            print(f"✗ Health check failed: {e}")
            return

        # 测试 2: 对话 - 列出工具
        print("\n[Test 2] Chat - List tools...")
        try:
            response = await client.post(
                f"{base_url}/chat",
                json={"message": "列出所有可用的工具"}
            )
            result = response.json()
            print(f"✓ Response:\n{result.get('response', result)}")
        except Exception as e:
            print(f"✗ Chat failed: {e}")

        # 测试 3: 对话 - 询问工具使用
        print("\n[Test 3] Chat - Ask about tool usage...")
        try:
            response = await client.post(
                f"{base_url}/chat",
                json={"message": "image_stitcher 工具怎么用？"}
            )
            result = response.json()
            print(f"✓ Response:\n{result['response']}")
        except Exception as e:
            print(f"✗ Chat failed: {e}")

        # 测试 4: 对话 - 请求创建工具
        print("\n[Test 4] Chat - Request tool creation...")
        try:
            response = await client.post(
                f"{base_url}/chat",
                json={"message": "我需要一个 PDF 转图片的工具"}
            )
            result = response.json()
            print(f"✓ Response:\n{result['response']}")
        except Exception as e:
            print(f"✗ Chat failed: {e}")

    print("\n" + "=" * 60)
    print("Tests completed")
    print("=" * 60)


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