#!/usr/bin/env python3
"""
Test script for AgentNEX MCP Server Backend Integration
Tests actual backend connectivity and tool execution
"""

import asyncio
import json
import sys
import os

# Add the project root to Python path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.client.backend_client import BackendClient
from app.mcp_server import call_tool
from app.core.config import settings


async def test_backend_integration():
    """Test backend integration functionality"""
    
    print("Testing AgentNEX Backend Integration...")
    print("=" * 50)
    
    # Initialize backend client
    backend_client = BackendClient()
    
    print(f"Backend URL: {settings.agentnex_backend_url}")
    print(f"API Key: {settings.agentnex_api_key[:10]}..." if len(settings.agentnex_api_key) > 10 else "Not set")
    
    try:
        # Test 1: Backend Health Check
        print("\n1. Testing backend connectivity...")
        try:
            health = await backend_client.health_check()
            if health:
                print("[OK] Backend is reachable and healthy")
            else:
                print("[WARN] Backend health check failed - may not be available")
        except Exception as e:
            print(f"[ERROR] Backend connection failed: {e}")
            print("   This is expected if backend is not running or API key is invalid")
        
        # Test 2: Test Device List (Read-only)
        print("\n2. Testing device list retrieval...")
        try:
            devices = await backend_client.get_devices()
            print(f"[OK] Retrieved {len(devices)} devices from backend")
            if devices:
                print(f"   Sample device: {devices[0].get('name', 'Unknown')} ({devices[0].get('id', 'No ID')[:8]}...)")
        except Exception as e:
            print(f"[ERROR] Device list failed: {e}")
            print("   This is expected if backend is not running or no devices exist")
        
        # Test 3: Test MCP Tool Call (with mock device ID)
        print("\n3. Testing MCP tool execution...")
        try:
            # Test get_device_telemetry with a mock device ID
            mock_device_id = "test-device-123"
            result = await call_tool("get_device_telemetry", {"device_id": mock_device_id})
            
            if result and len(result) > 0:
                response_text = result[0].text
                print("[OK] MCP tool execution successful")
                print(f"   Response length: {len(response_text)} characters")
                print(f"   Response preview: {response_text[:100]}...")
            else:
                print("[ERROR] MCP tool returned empty result")
                
        except Exception as e:
            print(f"[ERROR] MCP tool execution failed: {e}")
            print("   This is expected if backend is not running or device doesn't exist")
        
        # Test 4: Test Error Handling
        print("\n4. Testing error handling...")
        try:
            # Test with invalid device ID
            result = await call_tool("get_device_telemetry", {"device_id": "invalid-device-id"})
            
            if result and len(result) > 0:
                response_text = result[0].text
                if "Error" in response_text:
                    print("[OK] Error handling working correctly")
                    print(f"   Error response: {response_text[:100]}...")
                else:
                    print("[WARN] Expected error response but got success")
            
        except Exception as e:
            print(f"[OK] Exception handling working: {e}")
        
        print("\n" + "=" * 50)
        print("Backend Integration Test Summary:")
        print("[OK] MCP Server can instantiate BackendClient")
        print("[OK] Tool execution routing works")
        print("[OK] Error handling is implemented")
        print("[NOTE] Actual backend connectivity depends on:")
        print("   - Backend server running at configured URL")
        print("   - Valid API key in environment")
        print("   - Network connectivity")
        
        print("\nNext Steps for Full Integration:")
        print("1. Start AgentNEX Backend server")
        print("2. Set AGENTNEX_API_KEY environment variable")
        print("3. Test with real device IDs")
        print("4. Register MCP server with NEXA platform")
        
    except Exception as e:
        print(f"[ERROR] Integration test failed: {e}")
        import traceback
        traceback.print_exc()


async def test_tool_parameter_validation():
    """Test tool parameter validation"""
    
    print("\n" + "=" * 50)
    print("Testing Tool Parameter Validation...")
    
    test_cases = [
        # Valid cases
        ("get_device_telemetry", {"device_id": "test-123"}, True),
        ("restart_process", {"device_id": "test-123", "process_name": "chrome.exe"}, True),
        ("clear_cache", {"device_id": "test-123", "application": "chrome"}, True),
        
        # Invalid cases
        ("get_device_telemetry", {}, False),  # Missing device_id
        ("restart_process", {"device_id": "test-123"}, False),  # Missing process_name
        ("clear_cache", {"device_id": "test-123", "application": "invalid"}, False),  # Invalid application
    ]
    
    for tool_name, arguments, should_succeed in test_cases:
        try:
            result = await call_tool(tool_name, arguments)
            
            if result and len(result) > 0:
                response_text = result[0].text
                has_error = "Error" in response_text
                
                if should_succeed and not has_error:
                    print(f"[OK] {tool_name} with {arguments}: Success (expected)")
                elif not should_succeed and has_error:
                    print(f"[OK] {tool_name} with {arguments}: Error (expected)")
                elif should_succeed and has_error:
                    print(f"[WARN] {tool_name} with {arguments}: Error (unexpected)")
                else:
                    print(f"[WARN] {tool_name} with {arguments}: Success (unexpected)")
            
        except Exception as e:
            if should_succeed:
                print(f"[ERROR] {tool_name} with {arguments}: Exception (unexpected) - {e}")
            else:
                print(f"[OK] {tool_name} with {arguments}: Exception (expected) - {e}")


if __name__ == "__main__":
    asyncio.run(test_backend_integration())
    asyncio.run(test_tool_parameter_validation())
