#!/usr/bin/env python3
import asyncio
import json
import sys
import os

async def test_mcp():
    # 设置环境变量
    env = os.environ.copy()
    env['MIGADU_TEST_MODE'] = 'true'
    
    # 启动MCP服务器
    proc = await asyncio.create_subprocess_exec(
        *['uv', 'run', 'python', '-m', 'migadu_mcp.main'],
        stdin=asyncio.subprocess.PIPE,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        env=env,
        cwd='/app/auto-mcp-upload/data/9884'
    )
    
    # 初始化请求
    init_request = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {
                "name": "test-client",
                "version": "1.0.0"
            }
        }
    }
    
    # 发送初始化请求
    request_str = json.dumps(init_request) + '\n'
    proc.stdin.write(request_str.encode())
    await proc.stdin.drain()
    
    # 读取响应
    response_line = await proc.stdout.readline()
    if response_line:
        response = json.loads(response_line.decode())
        print(f"Initialize response: {json.dumps(response, indent=2)}")
        
        # 发送initialized通知
        initialized = {
            "jsonrpc": "2.0",
            "method": "notifications/initialized"
        }
        proc.stdin.write((json.dumps(initialized) + '\n').encode())
        await proc.stdin.drain()
        
        # 请求工具列表
        tools_request = {
            "jsonrpc": "2.0",
            "id": 2,
            "method": "tools/list",
            "params": {}
        }
        proc.stdin.write((json.dumps(tools_request) + '\n').encode())
        await proc.stdin.drain()
        
        # 读取工具列表响应
        tools_response = await proc.stdout.readline()
        if tools_response:
            tools_data = json.loads(tools_response.decode())
            print(f"\nTools response: {json.dumps(tools_data, indent=2)}")
            
            if 'result' in tools_data and 'tools' in tools_data['result']:
                tools = tools_data['result']['tools']
                print(f"\n✅ 找到 {len(tools)} 个工具:")
                for tool in tools:
                    print(f"  - {tool.get('name')}: {tool.get('description', '')[:80]}")
                return True
            else:
                print(f"\n❌ 响应中没有工具列表")
                return False
    
    proc.terminate()
    await proc.wait()
    return False

if __name__ == '__main__':
    success = asyncio.run(test_mcp())
    sys.exit(0 if success else 1)
