#!/usr/bin/env python3
"""MCP 서버 테스트 스크립트 - MCP 표준 프로토콜 사용"""

import sys
import os
import json
import requests

SERVER_URL = "http://localhost:5001/mcp"
DXF_FILE_PATH = "/home/windpacer/projects/ExperionCrawler/futurePlan/End-to-End P&ID Graph Pipeline/No-10_Plant_PID.dxf"

def make_mcp_request(method: str, params: dict, request_id: str = "test") -> dict:
    """MCP 표준 프로토콜로 요청"""
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json"
    }
    payload = {
        "jsonrpc": "2.0",
        "method": method,
        "params": params,
        "id": request_id
    }
    resp = requests.post(SERVER_URL, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.json()

def test_initialize():
    """initialize 도구 테스트"""
    print("=" * 60)
    print("1. initialize 테스트")
    print("=" * 60)
    try:
        result = make_mcp_request("initialize", {
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": {
                "name": "test-client",
                "version": "1.0.0"
            }
        })
        print(json.dumps(result, indent=2, ensure_ascii=False))
        return "result" in result
    except Exception as e:
        print(f"오류: {e}")
        return False

def test_list_tools():
    """tools/list 테스트"""
    print("\n" + "=" * 60)
    print("2. tools/list 테스트")
    print("=" * 60)
    try:
        result = make_mcp_request("tools/list", {})
        print(json.dumps(result, indent=2, ensure_ascii=False))
        if "result" in result and "tools" in result["result"]:
            print(f"\n✅ 등록된 도구 수: {len(result['result']['tools'])}")
            for tool in result["result"]["tools"]:
                print(f"  - {tool['name']}")
        return "result" in result
    except Exception as e:
        print(f"오류: {e}")
        return False

def test_call_tool():
    """tools/call 테스트"""
    print("\n" + "=" * 60)
    print("3. tools/call 테스트 (parse_pid_drawing)")
    print("=" * 60)
    try:
        result = make_mcp_request("tools/call", {
            "name": "parse_pid_drawing",
            "arguments": {
                "filepath": DXF_FILE_PATH
            }
        })
        print(json.dumps(result, indent=2, ensure_ascii=False))
        return "result" in result
    except Exception as e:
        print(f"오류: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    print("MCP 서버 테스트")
    print(f"서버 URL: {SERVER_URL}")
    print(f"DXF 파일: {DXF_FILE_PATH}")
    
    results = []
    results.append(("initialize", test_initialize()))
    results.append(("tools/list", test_list_tools()))
    results.append(("tools/call", test_call_tool()))
    
    print("\n" + "=" * 60)
    print("테스트 요약")
    print("=" * 60)
    for name, passed in results:
        status = "✅ 통과" if passed else "❌ 실패"
        print(f"{name}: {status}")
    
    all_passed = all(r[1] for r in results)
    if all_passed:
        print("\n🎉 모든 테스트 통과!")
        return 0
    else:
        print("\n⚠️ 일부 테스트 실패")
        return 1

if __name__ == "__main__":
    sys.exit(main())
