#!/bin/bash
# Comprehensive test suite for deployment functions:
# - mlgym_deployments_trigger
# - mlgym_deployments_get_status  
# - mlgym_deployments_list

set -e

PASSED=0
FAILED=0

echo "=== MCP Deployment Functions Test Suite ==="
echo ""

# Setup: Create user and project with deployment
echo "[SETUP] Creating test user and project with deployment"
TEST_EMAIL="deploy-$(date +%s)@example.com"
TEST_PASS="MyV3ryC0mpl3x!P@ssw0rd#2024"
CREATE_REQ="{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"mlgym_user_create\",\"arguments\":{\"email\":\"$TEST_EMAIL\",\"name\":\"Deploy Test\",\"password\":\"$TEST_PASS\",\"accept_terms\":true}},\"id\":1}"
CREATE_RESP=$(echo "$CREATE_REQ" | node index.js 2>/dev/null | tail -1)
USER_ID=$(echo "$CREATE_RESP" | jq -r '.result.content[0].text' | jq -r '.user_id')

if [ -n "$USER_ID" ] && [ "$USER_ID" != "null" ]; then
    echo "✅ Test user created (ID: $USER_ID)"
else
    echo "❌ Failed to create test user"
    exit 1
fi

# Create project WITH deployment enabled
PROJECT_NAME="deploy-test-$(date +%s | tail -c 6)"
PROJ_REQ="{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"mlgym_project_init\",\"arguments\":{\"name\":\"$PROJECT_NAME\",\"description\":\"Test project with deployment\",\"enable_deployment\":true}},\"id\":2}"
PROJ_RESP=$(echo "$PROJ_REQ" | node index.js 2>/dev/null | tail -1)
PROJ_CONTENT=$(echo "$PROJ_RESP" | jq -r '.result.content[0].text')
PROJECT_ID=$(echo "$PROJ_CONTENT" | jq -r '.project_id' 2>/dev/null)

if [ -n "$PROJECT_ID" ] && [ "$PROJECT_ID" != "null" ]; then
    echo "✅ Test project with deployment created (ID: $PROJECT_ID)"
else
    echo "❌ Failed to create test project"
    exit 1
fi

## TRIGGER DEPLOYMENT TESTS ##
echo ""
echo "=== mlgym_deployments_trigger Tests ==="
echo ""

# Test 1: Trigger without authentication
echo "Test 1: Trigger deployment without authentication"
rm -f ~/.mlgym/mcp_config.json
REQ="{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"mlgym_deployments_trigger\",\"arguments\":{\"project_id\":$PROJECT_ID}},\"id\":3}"
RESP=$(echo "$REQ" | node index.js 2>/dev/null | tail -1)
CONTENT=$(echo "$RESP" | jq -r '.result.content[0].text')
STATUS=$(echo "$CONTENT" | jq -r '.status')

if [ "$STATUS" = "error" ] && echo "$CONTENT" | grep -q "Not authenticated"; then
    echo "✅ Test 1: Correctly requires authentication"
    PASSED=$((PASSED + 1))
else
    echo "❌ Test 1: Should require authentication"
    FAILED=$((FAILED + 1))
fi

# Re-login
LOGIN_REQ="{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"mlgym_auth_login\",\"arguments\":{\"email\":\"$TEST_EMAIL\",\"password\":\"$TEST_PASS\"}},\"id\":4}"
echo "$LOGIN_REQ" | node index.js 2>/dev/null > /dev/null

# Test 2: Missing project_id
echo "Test 2: Trigger deployment without project_id"
REQ='{"jsonrpc":"2.0","method":"tools/call","params":{"name":"mlgym_deployments_trigger","arguments":{}},"id":5}'
RESP=$(echo "$REQ" | node index.js 2>/dev/null | tail -1)
CONTENT=$(echo "$RESP" | jq -r '.result.content[0].text')
STATUS=$(echo "$CONTENT" | jq -r '.status')

if [ "$STATUS" = "error" ] && echo "$CONTENT" | grep -q "required"; then
    echo "✅ Test 2: Correctly validates missing project_id"
    PASSED=$((PASSED + 1))
else
    echo "❌ Test 2: Should require project_id"
    FAILED=$((FAILED + 1))
fi

# Test 3: Trigger deployment with valid project
echo "Test 3: Trigger deployment with valid project"
TRIGGER_REQ="{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"mlgym_deployments_trigger\",\"arguments\":{\"project_id\":$PROJECT_ID}},\"id\":6}"
TRIGGER_RESP=$(echo "$TRIGGER_REQ" | node index.js 2>/dev/null | tail -1)
TRIGGER_CONTENT=$(echo "$TRIGGER_RESP" | jq -r '.result.content[0].text')
TRIGGER_STATUS=$(echo "$TRIGGER_CONTENT" | jq -r '.status')

DEPLOYMENT_ID=""
if [ "$TRIGGER_STATUS" = "success" ]; then
    DEPLOYMENT_ID=$(echo "$TRIGGER_CONTENT" | jq -r '.deployment_id')
    echo "✅ Test 3: Deployment triggered (ID: $DEPLOYMENT_ID)"
    PASSED=$((PASSED + 1))
else
    echo "❌ Test 3: Deployment trigger failed - $(echo "$TRIGGER_CONTENT" | jq -r '.message')"
    FAILED=$((FAILED + 1))
fi

## GET STATUS TESTS ##
echo ""
echo "=== mlgym_deployments_get_status Tests ==="
echo ""

# Test 4: Get status without parameters
echo "Test 4: Get status without parameters"
REQ='{"jsonrpc":"2.0","method":"tools/call","params":{"name":"mlgym_deployments_get_status","arguments":{}},"id":7}'
RESP=$(echo "$REQ" | node index.js 2>/dev/null | tail -1)
CONTENT=$(echo "$RESP" | jq -r '.result.content[0].text')
STATUS=$(echo "$CONTENT" | jq -r '.status')

if [ "$STATUS" = "error" ]; then
    echo "✅ Test 4: Correctly requires deployment_id or project_id"
    PASSED=$((PASSED + 1))
else
    echo "❌ Test 4: Should require at least one parameter"
    FAILED=$((FAILED + 1))
fi

# Test 5: Get status with project_id
if [ -n "$PROJECT_ID" ]; then
    echo "Test 5: Get status with project_id"
    STATUS_REQ="{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"mlgym_deployments_get_status\",\"arguments\":{\"project_id\":$PROJECT_ID}},\"id\":8}"
    STATUS_RESP=$(echo "$STATUS_REQ" | node index.js 2>/dev/null | tail -1)
    STATUS_CONTENT=$(echo "$STATUS_RESP" | jq -r '.result.content[0].text')
    STATUS_STATUS=$(echo "$STATUS_CONTENT" | jq -r '.status')
    
    if [ "$STATUS_STATUS" = "success" ] || [ "$STATUS_STATUS" = "error" ]; then
        echo "✅ Test 5: Get status returned response"
        PASSED=$((PASSED + 1))
    else
        echo "❌ Test 5: Get status failed"
        FAILED=$((FAILED + 1))
    fi
fi

## LIST DEPLOYMENTS TESTS ##
echo ""
echo "=== mlgym_deployments_list Tests ==="
echo ""

# Test 6: List deployments without authentication
echo "Test 6: List deployments without authentication"
rm -f ~/.mlgym/mcp_config.json
REQ='{"jsonrpc":"2.0","method":"tools/call","params":{"name":"mlgym_deployments_list","arguments":{}},"id":9}'
RESP=$(echo "$REQ" | node index.js 2>/dev/null | tail -1)
CONTENT=$(echo "$RESP" | jq -r '.result.content[0].text')
STATUS=$(echo "$CONTENT" | jq -r '.status')

if [ "$STATUS" = "error" ] && echo "$CONTENT" | grep -q "Not authenticated"; then
    echo "✅ Test 6: Correctly requires authentication"
    PASSED=$((PASSED + 1))
else
    echo "❌ Test 6: Should require authentication"
    FAILED=$((FAILED + 1))
fi

# Re-login
echo "$LOGIN_REQ" | node index.js 2>/dev/null > /dev/null

# Test 7: List all deployments
echo "Test 7: List all deployments"
LIST_REQ='{"jsonrpc":"2.0","method":"tools/call","params":{"name":"mlgym_deployments_list","arguments":{}},"id":10}'
LIST_RESP=$(echo "$LIST_REQ" | node index.js 2>/dev/null | tail -1)
LIST_CONTENT=$(echo "$LIST_RESP" | jq -r '.result.content[0].text')
LIST_STATUS=$(echo "$LIST_CONTENT" | jq -r '.status')

if [ "$LIST_STATUS" = "success" ]; then
    DEPLOY_COUNT=$(echo "$LIST_CONTENT" | jq -r '.total' 2>/dev/null)
    echo "✅ Test 7: List deployments successful (count: $DEPLOY_COUNT)"
    PASSED=$((PASSED + 1))
else
    echo "❌ Test 7: List deployments failed"
    FAILED=$((FAILED + 1))
fi

# Test 8: List deployments for specific project
echo "Test 8: List deployments for specific project"
PROJ_LIST_REQ="{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"mlgym_deployments_list\",\"arguments\":{\"project_id\":$PROJECT_ID}},\"id\":11}"
PROJ_LIST_RESP=$(echo "$PROJ_LIST_REQ" | node index.js 2>/dev/null | tail -1)
PROJ_LIST_CONTENT=$(echo "$PROJ_LIST_RESP" | jq -r '.result.content[0].text')
PROJ_LIST_STATUS=$(echo "$PROJ_LIST_CONTENT" | jq -r '.status')

if [ "$PROJ_LIST_STATUS" = "success" ] || [ "$PROJ_LIST_STATUS" = "error" ]; then
    echo "✅ Test 8: List project deployments returned response"
    PASSED=$((PASSED + 1))
else
    echo "❌ Test 8: List project deployments failed"
    FAILED=$((FAILED + 1))
fi

echo ""
echo "==============================================="
echo "RESULTS: $PASSED passed, $FAILED failed (Total: $((PASSED + FAILED)))"
echo "==============================================="

if [ $FAILED -eq 0 ]; then
    echo "✅ ALL TESTS PASSED"
    exit 0
else
    echo "⚠️  SOME TESTS FAILED"
    exit 1
fi
