"""Test script for HTTP channel with session support and long-polling."""

import asyncio
import json
import base64
import httpx


async def test_blocking_session():
    """Test blocking mode with session support."""
    print("=" * 60)
    print("测试 1: 长连接阻塞 + 会话 Session")
    print("=" * 60)
    
    chat_id = "test_session_001"
    
    # 第一轮对话
    print("\n第一轮对话...")
    payload = {
        "sender_id": "user123",
        "chat_id": chat_id,
        "content": "你好",
        "metadata": {
            "session_id": chat_id
        }
    }

    try:
        async with httpx.AsyncClient(timeout=120) as client:
            response = await client.post(
                "http://localhost:18770/api/message",
                json=payload,
                headers={"Content-Type": "application/json"}
            )

            if response.status_code == 200:
                result = response.json()
                print(f"✓ 请求已接收: {result.get('status')}")
                print(f"  响应: {json.dumps(result, ensure_ascii=False, indent=2)}")
                
                # 检查是否有 agent 响应
                if result.get('status') == 'success':
                    print(f"\nAgent 响应:")
                    print(f"  内容: {result.get('content', '')[:100]}...")
                    print(f"  会话 ID: {result.get('chat_id')}")
                elif result.get('status') == 'error':
                    print(f"\n错误: {result.get('message')}")
            else:
                print(f"✗ 请求失败: {response.status_code}")
                print(f"  响应: {response.text}")
    except Exception as e:
        print(f"✗ 请求错误: {e}")

    # 等待一下
    await asyncio.sleep(2)

    # 第二轮对话（使用相同的 chat_id）
    print("\n第二轮对话（相同会话）...")
    payload = {
        "sender_id": "user123",
        "chat_id": chat_id,
        "content": "帮我找一个LED驱动电路的原理图",
        "metadata": {
            "session_id": chat_id
        }
    }

    try:
        async with httpx.AsyncClient(timeout=120) as client:
            response = await client.post(
                "http://localhost:18770/api/message",
                json=payload,
                headers={"Content-Type": "application/json"}
            )

            if response.status_code == 200:
                result = response.json()
                print(f"✓ 请求已接收: {result.get('status')}")
                print(f"  响应: {json.dumps(result, ensure_ascii=False, indent=2)}")
                
                if result.get('status') == 'success':
                    print(f"\nAgent 响应:")
                    print(f"  内容: {result.get('content', '')[:100]}...")
                    print(f"  会话 ID: {result.get('chat_id')}")
                elif result.get('status') == 'error':
                    print(f"\n错误: {result.get('message')}")
            else:
                print(f"✗ 请求失败: {response.status_code}")
                print(f"  响应: {response.text}")
    except Exception as e:
        print(f"✗ 请求错误: {e}")


async def test_streaming_session():
    """Test streaming mode with session support."""
    print("\n" + "=" * 60)
    print("测试 2: 流式响应 + 会话 Session")
    print("=" * 60)
    
    chat_id = "test_session_002"
    
    # 流式请求
    print("\n发送流式请求...")
    payload = {
        "sender_id": "user123",
        "chat_id": chat_id,
        "content": "帮我找一个LED驱动电路的原理图",
        "metadata": {
            "session_id": chat_id
        }
    }

    try:
        async with httpx.AsyncClient(timeout=120) as client:
            async with client.stream(
                "POST",
                "http://localhost:18770/api/stream",
                json=payload,
                headers={"Content-Type": "application/json"}
            ) as response:
                if response.status_code == 200:
                    print("✓ 流式连接成功")
                    print(f"  Content-Type: {response.headers.get('content-type')}")
                    print("\n开始接收流式响应...\n")
                    
                    async for line in response.aiter_lines():
                        if line.strip():
                            # 解析 SSE 事件
                            if line.startswith("event:"):
                                event_type = line.split(":", 1)[1].strip()
                            elif line.startswith("data:"):
                                try:
                                    data = json.loads(line.split(":", 1)[1].strip())
                                    
                                    if event_type == "message":
                                        print(f"\n收到消息事件:")
                                        print(f"  内容: {data.get('content', '')[:100]}...")
                                        print(f"  会话 ID: {data.get('chat_id')}")
                                    elif event_type == "done":
                                        print("\n✓ 流式响应完成")
                                        break
                                except json.JSONDecodeError as e:
                                    print(f"  JSON 解析错误: {e}")
                else:
                    print(f"✗ 流式连接失败: {response.status_code}")
                    print(f"  响应: {response.text}")
    except Exception as e:
        print(f"✗ 流式测试错误: {e}")


async def test_multi_turn_conversation():
    """Test multi-turn conversation with blocking mode."""
    print("\n" + "=" * 60)
    print("测试 3: 多轮对话")
    print("=" * 60)
    
    chat_id = "test_session_003"
    
    # 多轮对话
    questions = [
        "你好",
        "帮我找一个LED驱动电路的原理图",
        "这个方案怎么样？",
        "还有其他方案吗？"
    ]
    
    for i, question in enumerate(questions, 1):
        print(f"\n第 {i} 轮对话...")
        payload = {
            "sender_id": "user123",
            "chat_id": chat_id,
            "content": question,
            "metadata": {
                "session_id": chat_id,
                "turn": i
            }
        }

        try:
            async with httpx.AsyncClient(timeout=120) as client:
                response = await client.post(
                    "http://localhost:18770/api/message",
                    json=payload,
                    headers={"Content-Type": "application/json"}
                )

                if response.status_code == 200:
                    result = response.json()
                    print(f"✓ 请求已接收")
                    
                    if result.get('status') == 'success':
                        content = result.get('content', '')
                        if content:
                            print(f"  Agent 响应: {content[:100]}...")
                        else:
                            print(f"  Agent 响应: (无内容)")
                    elif result.get('status') == 'error':
                        print(f"  错误: {result.get('message')}")
                else:
                    print(f"✗ 请求失败: {response.status_code}")
        except Exception as e:
            print(f"✗ 请求错误: {e}")
        
        # 等待一下再发送下一轮
        await asyncio.sleep(1)


async def test_health_check():
    """Test health check endpoint."""
    print("\n" + "=" * 60)
    print("测试 4: 健康检查")
    print("=" * 60)
    
    try:
        async with httpx.AsyncClient(timeout=30) as client:
            response = await client.get("http://localhost:18770/health")

            if response.status_code == 200:
                print("✓ 健康检查通过")
                print(f"  响应: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
            else:
                print(f"✗ 健康检查失败: {response.status_code}")
    except Exception as e:
        print(f"✗ 健康检查错误: {e}")


async def main():
    """Main test function."""
    print("=" * 60)
    print("HTTP Channel 测试（长连接 + 会话 Session）")
    print("=" * 60)
    print("\n请确保:")
    print("1. asedclaw 已启动并启用了 HTTP channel")
    print("2. HTTP channel 监听在 http://localhost:18770")
    print("3. schematic-search skill 已安装")
    print("4. 配置文件中的 maxTokens 已修改为合理值\n")

    print("\n测试选项:")
    print("  1. 长连接阻塞 + 会话 Session")
    print("  2. 流式响应 + 会话 Session")
    print("  3. 多轮对话测试")
    print("  4. 健康检查")
    print("  5. 全部测试")
    
    choice = input("\n请选择 (1/2/3/4/5, 默认 1): ").strip() or "1"

    if choice == "1":
        await test_blocking_session()
    elif choice == "2":
        await test_streaming_session()
    elif choice == "3":
        await test_multi_turn_conversation()
    elif choice == "4":
        await test_health_check()
    elif choice == "5":
        print("\n开始全部测试...\n")
        await test_health_check()
        await test_blocking_session()
        await test_streaming_session()
        await test_multi_turn_conversation()
        print("\n✓ 全部测试完成")
    else:
        print(f"无效选择: {choice}")


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