#!/bin/bash
set -e

SERVER_DIR="$1"
SERVER_LOG="/tmp/hermes-verify-mcp-server.log"

# Check dependencies
if ! command -v uvicorn &> /dev/null; then
    echo "ERROR: uvicorn not installed. Run: pip install uvicorn fastapi python-multipart"
    exit 1
fi

# Start server
echo "Starting MCP server..."
cd "$SERVER_DIR" 
uvicorn server:app --host 0.0.0.0 --port 8900 > "$SERVER_LOG" 2>&1 &
SERVER_PID=$!
sleep 3

# Verify server
if ! ps -p $SERVER_PID > /dev/null; then
    echo "FAIL: Server failed to start"
    cat "$SERVER_LOG"
    exit 1
fi

# Test endpoints
test_endpoint() {
    echo -n "Testing $1... "
    RESPONSE=$(curl -s -X "$2" "$3" -d "$4" -H "Content-Type: application/json")
    [[ "$RESPONSE" == *"Not Found"* ]] && echo "FAIL (404)" || echo "PASS"
}

test_endpoint "list_directory" "GET" "http://localhost:8900/list_directory?path=/root/docker" ""
test_endpoint "read_file" "GET" "http://localhost:8900/read_file?path=/root/docker/mcp-filesystem/server.py&max_lines=5" ""
test_endpoint "write_file" "POST" "http://localhost:8900/write_file" '{"path":"/root/docker/mcp-filesystem/test.txt","content":"test"}'
test_endpoint "search_files" "GET" "http://localhost:8900/search_files?pattern=*.py&directory=/root/docker/mcp-filesystem" ""
test_endpoint "create_directory" "POST" "http://localhost:8900/create_directory" '{"path":"/root/docker/mcp-filesystem/test_dir"}'

# Cleanup
kill $SERVER_PID
rm "$SERVER_LOG"