#!/usr/bin/env python3
"""Test MCP server connection to backend."""

import asyncio
import os
from app.client.backend_client import BackendClient

# Set environment variables
os.environ['AGENTNEX_BACKEND_URL'] = 'http://localhost:8000'
os.environ['AGENTNEX_API_KEY'] = 'change-me-in-production-internal-api-key'

async def test_backend():
    print("=" * 60)
    print("TESTING BACKEND CONNECTION")
    print("=" * 60)
    
    print(f"\nBackend URL: {os.environ['AGENTNEX_BACKEND_URL']}")
    print(f"API Key: {os.environ['AGENTNEX_API_KEY'][:20]}...")
    
    # Create backend client
    client = BackendClient()
    
    # Test 1: Health Check
    print("\n[Test 1] Health Check...")
    try:
        healthy = await client.health_check()
        if healthy:
            print("[PASS] Backend is healthy")
        else:
            print("[FAIL] Backend health check failed")
    except Exception as e:
        print(f"[ERROR] {e}")
    
    # Test 2: Get Devices
    print("\n[Test 2] Get Devices List...")
    try:
        devices = await client.get_devices()
        print(f"[PASS] Retrieved {len(devices)} device(s)")
        if devices:
            print("\nDevices:")
            for i, device in enumerate(devices[:3], 1):  # Show first 3
                print(f"  {i}. {device.get('device_id', 'N/A')} - {device.get('status', 'N/A')}")
            if len(devices) > 3:
                print(f"  ... and {len(devices) - 3} more")
    except Exception as e:
        print(f"[ERROR] {e}")
    
    # Test 3: Get Device Status (if devices exist)
    if devices:
        device_id = devices[0].get('device_id')
        print(f"\n[Test 3] Get Device Status for {device_id}...")
        try:
            status = await client.get_device_status(device_id)
            print(f"[PASS] Device status = {status.get('status', 'N/A')}")
            print(f"  Connected: {status.get('is_connected', 'N/A')}")
            print(f"  Last seen: {status.get('last_seen', 'N/A')}")
        except Exception as e:
            print(f"[ERROR] {e}")
        
        # Test 4: Get Device Telemetry
        print(f"\n[Test 4] Get Device Telemetry for {device_id}...")
        try:
            telemetry = await client.get_device_telemetry(device_id)
            print(f"[PASS] Got telemetry data")
            if 'cpu' in telemetry:
                print(f"  CPU: {telemetry['cpu'].get('usage_percent', 'N/A')}%")
            if 'memory' in telemetry:
                print(f"  Memory: {telemetry['memory'].get('usage_percent', 'N/A')}%")
            if 'disk' in telemetry:
                print(f"  Disk: {telemetry['disk'].get('usage_percent', 'N/A')}%")
        except Exception as e:
            print(f"[ERROR] {e}")
    
    print("\n" + "=" * 60)
    print("BACKEND CONNECTION TESTS COMPLETE")
    print("=" * 60)

if __name__ == "__main__":
    asyncio.run(test_backend())
