#!/usr/bin/env python3
import asyncio
import json
import sys
from pathlib import Path

# 添加src路径
sys.path.insert(0, str(Path(__file__).parent / 'src'))

from mcpagentai.server import start_server

async def test():
    """测试MCP服务器"""
    print("Testing MCP server communication...")
    
    # 创建测试进程
    proc = await asyncio.create_subprocess_exec(
        sys.executable, '-m', 'mcpagentai',
        stdin=asyncio.subprocess.PIPE,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )
    
    print("Process started, waiting for initialization...")
    await asyncio.sleep(2)
    
    # 检查进程状态
    if proc.returncode is not None:
        stdout, stderr = await proc.communicate()
        print(f"Process exited with code {proc.returncode}")
        print(f"Stdout: {stdout.decode()}")
        print(f"Stderr: {stderr.decode()}")
        return False
    
    print("Process still running, sending initialization request...")
    
    # 发送初始化请求
    init_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {
                "name": "test-client",
                "version": "1.0.0"
            }
        }
    }
    
    request_json = json.dumps(init_request) + '\n'
    print(f"Sending: {request_json.strip()}")
    
    try:
        proc.stdin.write(request_json.encode())
        await proc.stdin.drain()
        print("Request sent successfully")
    except Exception as e:
        print(f"Failed to send request: {e}")
        proc.terminate()
        await proc.wait()
        return False
    
    # 读取响应
    try:
        print("Waiting for response...")
        response = await asyncio.wait_for(proc.stdout.readline(), timeout=5)
        if response:
            print(f"Received: {response.decode().strip()}")
            try:
                response_data = json.loads(response.decode().strip())
                print(f"Parsed response: {json.dumps(response_data, indent=2)}")
                return True
            except json.JSONDecodeError:
                print("Failed to parse JSON response")
                return False
        else:
            print("No response received")
            return False
    except asyncio.TimeoutError:
        print("Timeout waiting for response")
        return False
    except Exception as e:
        print(f"Error reading response: {e}")
        return False
    finally:
        # 清理
        print("Cleaning up...")
        try:
            proc.terminate()
            await asyncio.wait_for(proc.wait(), timeout=2)
        except asyncio.TimeoutError:
            proc.kill()
            await proc.wait()

if __name__ == "__main__":
    result = asyncio.run(test())
    print(f"\nTest result: {'PASS' if result else 'FAIL'}")
    sys.exit(0 if result else 1)
