#!/bin/bash
# Quick connection test script for Proxmox MCP Server

set -e

ENV_FILE="$HOME/.env"

echo "🔍 Testing Proxmox MCP Server Connection"
echo "========================================"
echo ""

# Load environment variables
if [ -f "$ENV_FILE" ]; then
    source <(grep -E "^PROXMOX_" "$ENV_FILE" | sed 's/^/export /')
else
    echo "❌ .env file not found at $ENV_FILE"
    exit 1
fi

echo "Connection Details:"
echo "  Host: ${PROXMOX_HOST:-not set}"
echo "  User: ${PROXMOX_USER:-not set}"
echo "  Token: ${PROXMOX_TOKEN_NAME:-not set}"
echo "  Port: ${PROXMOX_PORT:-8006}"
echo ""

# Test 1: Direct API connection
echo "Test 1: Direct Proxmox API Connection"
echo "--------------------------------------"
if [ -z "$PROXMOX_TOKEN_VALUE" ] || [ "$PROXMOX_TOKEN_VALUE" = "your-token-secret-here" ]; then
    echo "⚠️  Token value not configured"
else
    API_RESPONSE=$(curl -s -k -H "Authorization: PVEAPIToken=${PROXMOX_USER}!${PROXMOX_TOKEN_NAME}=${PROXMOX_TOKEN_VALUE}" \
        "https://${PROXMOX_HOST}:${PROXMOX_PORT:-8006}/api2/json/version" 2>&1)
    
    if echo "$API_RESPONSE" | grep -q "data"; then
        VERSION=$(echo "$API_RESPONSE" | grep -oP '"data":{"version":"\K[^"]+')
        echo "✅ API connection successful"
        echo "   Proxmox version: $VERSION"
    else
        echo "❌ API connection failed"
        echo "   Response: $API_RESPONSE"
    fi
fi

echo ""
echo "Test 2: MCP Server Tool List"
echo "-----------------------------"
cd "$(dirname "$0")/../mcp-proxmox" || exit 1

TIMEOUT=5
REQUEST='{"jsonrpc":"2.0","id":1,"method":"tools/list"}'

RESPONSE=$(timeout $TIMEOUT node index.js <<< "$REQUEST" 2>&1 | grep -E "^\{" || echo "")

if echo "$RESPONSE" | grep -q "tools"; then
    TOOL_COUNT=$(echo "$RESPONSE" | grep -o '"name"' | wc -l)
    echo "✅ MCP server responding"
    echo "   Tools available: $TOOL_COUNT"
else
    echo "⚠️  MCP server response unclear"
    echo "   Response preview: $(echo "$RESPONSE" | head -c 100)..."
fi

echo ""
echo "Test 3: Get Proxmox Nodes"
echo "-------------------------"
REQUEST='{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"proxmox_get_nodes","arguments":{}}}'

RESPONSE=$(timeout $TIMEOUT node index.js <<< "$REQUEST" 2>&1 | grep -E "^\{" || echo "")

if echo "$RESPONSE" | grep -q "data\|nodes\|Node"; then
    echo "✅ Successfully retrieved Proxmox nodes"
    NODES=$(echo "$RESPONSE" | grep -oP '"text":"[^"]*Node[^"]*"' | head -3 || echo "")
    if [ -n "$NODES" ]; then
        echo "$NODES" | sed 's/"text":"/   /' | sed 's/"$//'
    fi
else
    ERROR=$(echo "$RESPONSE" | grep -oP '"message":"\K[^"]*' || echo "Unknown error")
    echo "⚠️  Could not retrieve nodes"
    echo "   Error: $ERROR"
fi

echo ""
echo "========================================"
echo "Connection test complete!"
echo ""
echo "If all tests passed, your MCP server is ready to use."
echo "Start it with: pnpm mcp:start"

