#!/usr/bin/env python3
"""Test MCP HTTP API endpoints."""

import requests
import json

BASE_URL = "http://localhost:8001"

def test_endpoint(method, endpoint, data=None, description=""):
    """Test a single endpoint."""
    url = f"{BASE_URL}{endpoint}"
    print(f"\n{description}")
    print(f"  {method} {url}")
    
    try:
        if method == "GET":
            response = requests.get(url, timeout=5)
        elif method == "POST":
            response = requests.post(url, json=data, timeout=5)
        
        print(f"  Status: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            print(f"  [SUCCESS]")
            return result
        else:
            print(f"  [FAILED] {response.text[:200]}")
            return None
    
    except requests.exceptions.ConnectionError:
        print(f"  [ERROR] Cannot connect to {BASE_URL}")
        print(f"  Make sure MCP HTTP server is running:")
        print(f"    python run_http_server.py")
        return None
    except Exception as e:
        print(f"  [ERROR] {e}")
        return None

def main():
    print("=" * 70)
    print("TESTING MCP HTTP API ENDPOINTS")
    print("=" * 70)
    print(f"\nBase URL: {BASE_URL}")
    print("\nNOTE: Make sure HTTP server is running: python run_http_server.py")
    
    # Test 1: Health Check
    result = test_endpoint("GET", "/health", description="[Test 1] Health Check")
    
    # Test 2: Root Endpoint
    result = test_endpoint("GET", "/", description="[Test 2] Root / Service Info")
    
    # Test 3: List Tools
    result = test_endpoint("GET", "/mcp/tools", description="[Test 3] List MCP Tools")
    if result and 'tools' in result:
        print(f"  Tools count: {len(result['tools'])}")
        for i, tool in enumerate(result['tools'][:3], 1):
            print(f"    {i}. {tool['name']}")
    
    # Test 4: List Resources
    result = test_endpoint("GET", "/mcp/resources", description="[Test 4] List MCP Resources")
    if result and 'resources' in result:
        print(f"  Resources count: {len(result['resources'])}")
        for i, res in enumerate(result['resources'][:3], 1):
            print(f"    {i}. {res['uri']}")
    
    # Test 5: Read Resource (All Devices)
    data = {"uri": "agentnex://devices/all"}
    result = test_endpoint("POST", "/mcp/resources/read", data=data, 
                          description="[Test 5] Read Resource (All Devices)")
    if result and 'content' in result:
        try:
            content = json.loads(result['content']) if isinstance(result['content'], str) else result['content']
            if isinstance(content, list):
                print(f"  Devices found: {len(content)}")
                for i, dev in enumerate(content[:3], 1):
                    device_id = dev.get('device_id', 'N/A')
                    status = dev.get('status', 'N/A')
                    print(f"    {i}. {device_id} - {status}")
        except:
            pass
    
    # Test 6: Call Tool (Get Device Telemetry) - requires device_id
    # This will fail if no devices, but tests the endpoint structure
    data = {
        "name": "get_device_telemetry",
        "arguments": {"device_id": "test-device-id"}
    }
    result = test_endpoint("POST", "/mcp/tools/call", data=data,
                          description="[Test 6] Call Tool (Get Device Telemetry)")
    
    print("\n" + "=" * 70)
    print("HTTP API TESTS COMPLETE")
    print("=" * 70)
    print("\nIf tests failed with connection error, run:")
    print("  python run_http_server.py")
    print("\nThen run this test again:")
    print("  python test_http_api.py")

if __name__ == "__main__":
    main()
