"""
Test MCP Server with Production Backend
Backend: https://agentnex-cursorback-qa1-708341704774.us-central1.run.app/
API Key: xDGxeHYEiq0mu0eU
"""
import asyncio
import sys
import os

# Set environment variables BEFORE importing
os.environ["AGENTNEX_BACKEND_URL"] = "https://agentnex-cursorback-qa1-708341704774.us-central1.run.app"
os.environ["AGENTNEX_API_KEY"] = "xDGxeHYEiq0mu0eU"

print("=" * 80)
print("MCP SERVER PRODUCTION TEST")
print("=" * 80)
print(f"\nBackend URL: {os.environ['AGENTNEX_BACKEND_URL']}")
print(f"API Key: {os.environ['AGENTNEX_API_KEY'][:8]}...")
print("=" * 80)

async def test_production_backend():
    """Test MCP server with production backend"""
    
    try:
        print("\n[1] IMPORTING MCP SERVER...")
        from app.mcp_server import tools, resources, backend_client
        from app.core.config import settings
        print(f"    [PASS] Import successful")
        print(f"    Backend URL: {settings.agentnex_backend_url}")
        print(f"    API Key: {settings.agentnex_api_key[:8]}...")
        
        print("\n[2] TESTING BACKEND CONNECTION...")
        try:
            health = await backend_client.health_check()
            if health:
                print(f"    [PASS] Backend is reachable!")
                print(f"    Status: Connected")
            else:
                print(f"    [WARN] Backend health check returned False")
                print(f"    Backend might be down or unreachable")
        except Exception as e:
            print(f"    [ERROR] Backend connection failed: {e}")
            print(f"    Make sure backend is running and accessible")
            return False
        
        print("\n[3] LISTING ALL TOOLS...")
        print(f"    Total tools: {len(tools)}")
        for i, tool in enumerate(tools, 1):
            print(f"    [{i}] {tool.name}")
        
        print("\n[4] LISTING ALL RESOURCES...")
        print(f"    Total resources: {len(resources)}")
        for i, resource in enumerate(resources, 1):
            print(f"    [{i}] {resource.uri}")
        
        print("\n[5] TESTING TOOLS CONVERSION TO MCP FORMAT...")
        mcp_tools = [tool.to_mcp_tool() for tool in tools]
        print(f"    [PASS] All {len(mcp_tools)} tools converted to MCP format")
        
        print("\n[6] TESTING RESOURCES CONVERSION TO MCP FORMAT...")
        mcp_resources = [resource.to_mcp_resource() for resource in resources]
        print(f"    [PASS] All {len(mcp_resources)} resources converted to MCP format")
        
        print("\n[7] TESTING BACKEND API CALLS...")
        
        # Test: Get all devices
        print("\n    [7.1] Testing: Get All Devices")
        try:
            devices = await backend_client.get_devices()
            print(f"    [PASS] Retrieved {len(devices)} devices")
            
            if len(devices) > 0:
                print(f"\n    Sample Device:")
                device = devices[0]
                print(f"      - ID: {device.get('id', 'N/A')}")
                print(f"      - Name: {device.get('name', 'N/A')}")
                print(f"      - Hostname: {device.get('hostname', 'N/A')}")
                print(f"      - Status: {device.get('status', 'N/A')}")
                print(f"      - OS: {device.get('os_name', 'N/A')} {device.get('os_version', 'N/A')}")
                
                # Test: Get device telemetry if device exists
                device_id = device.get('id')
                if device_id:
                    print(f"\n    [7.2] Testing: Get Device Telemetry (Device: {device.get('name', 'N/A')})")
                    try:
                        telemetry = await backend_client.get_device_telemetry(device_id)
                        print(f"    [PASS] Retrieved telemetry data")
                        print(f"      - CPU: {telemetry.get('cpu_percent', 'N/A')}%")
                        print(f"      - Memory: {telemetry.get('memory_percent', 'N/A')}%")
                        print(f"      - Disk: {telemetry.get('disk_percent', 'N/A')}%")
                    except Exception as e:
                        print(f"    [WARN] Could not get telemetry: {e}")
                    
                    # Test: Get device processes
                    print(f"\n    [7.3] Testing: Get Device Processes")
                    try:
                        processes = await backend_client.get_device_processes(device_id)
                        print(f"    [PASS] Retrieved {len(processes)} processes")
                        if len(processes) > 0:
                            print(f"\n    Top 3 Processes by CPU:")
                            sorted_procs = sorted(processes, key=lambda p: p.get('cpu_percent', 0), reverse=True)[:3]
                            for proc in sorted_procs:
                                print(f"      - {proc.get('name', 'N/A')}: CPU {proc.get('cpu_percent', 0)}%, Memory {proc.get('memory_percent', 0)}%")
                    except Exception as e:
                        print(f"    [WARN] Could not get processes: {e}")
            else:
                print(f"    [INFO] No devices found in backend")
                print(f"    [INFO] Make sure devices are registered and online")
        
        except Exception as e:
            print(f"    [ERROR] Failed to get devices: {e}")
            return False
        
        print("\n[8] TESTING MCP TOOL EXECUTION FORMAT...")
        
        # Test tool execution structure (without actually executing)
        print(f"\n    Testing tool: {tools[0].name}")
        sample_tool = tools[0]
        print(f"    - Name: {sample_tool.name}")
        print(f"    - Description: {sample_tool.description[:80]}...")
        print(f"    - Input Schema: {sample_tool.input_schema}")
        print(f"    [PASS] Tool structure is valid")
        
        print("\n" + "=" * 80)
        print("PRODUCTION TEST SUMMARY")
        print("=" * 80)
        print("[PASS] Backend Connection: SUCCESS")
        print(f"[PASS] Tools Available: {len(tools)}")
        print(f"[PASS] Resources Available: {len(resources)}")
        print("[PASS] MCP Format Conversion: SUCCESS")
        print("[PASS] Backend API Calls: SUCCESS")
        print("=" * 80)
        
        print("\n" + "=" * 80)
        print("MCP SERVER IS READY FOR PRODUCTION USE!")
        print("=" * 80)
        print("\nAll components are working correctly:")
        print("  1. Backend connection established")
        print("  2. All tools and resources loaded")
        print("  3. MCP protocol format validated")
        print("  4. Backend API integration verified")
        print("\nThe MCP server can now be used with:")
        print("  - NEXA AI Platform (via stdio)")
        print("  - Any MCP-compatible client")
        print("  - Custom integrations")
        print("=" * 80)
        
        return True
        
    except Exception as e:
        print(f"\n[FAIL] Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False

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