#!/bin/bash

# AtlasOS - Calypso Monitoring API Test Script
# Tests Enhanced Monitoring endpoints: alerts, metrics, health, WebSocket

set -e

# Configuration
API_URL="${API_URL:-http://localhost:8080}"
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASS="${ADMIN_PASS:-admin123}"
TOKEN_FILE="/tmp/calypso-token.txt"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[✓]${NC} $1"
}

log_error() {
    echo -e "${RED}[✗]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[!]${NC} $1"
}

# Test endpoint helper
test_endpoint() {
    local method=$1
    local endpoint=$2
    local data=$3
    local description=$4
    local require_auth=${5:-true}
    
    log_info "Testing: $description"
    
    local headers="Content-Type: application/json"
    if [ "$require_auth" = "true" ]; then
        if [ ! -f "$TOKEN_FILE" ]; then
            log_error "No authentication token found. Please login first."
            return 1
        fi
        local token=$(cat "$TOKEN_FILE")
        headers="$headers\nAuthorization: Bearer $token"
    fi
    
    local response
    if [ -n "$data" ]; then
        response=$(curl -s -w "\n%{http_code}" -X "$method" "$API_URL$endpoint" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $token" \
            -d "$data" 2>/dev/null || echo -e "\n000")
    else
        response=$(curl -s -w "\n%{http_code}" -X "$method" "$API_URL$endpoint" \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $token" \
            2>/dev/null || echo -e "\n000")
    fi
    
    local http_code=$(echo "$response" | tail -n1)
    local body=$(echo "$response" | sed '$d')
    
    if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
        log_success "$description (HTTP $http_code)"
        echo "$body" | jq . 2>/dev/null || echo "$body"
        return 0
    else
        log_error "$description failed (HTTP $http_code)"
        echo "$body" | jq . 2>/dev/null || echo "$body"
        return 1
    fi
}

# Main test flow
main() {
    log_info "=========================================="
    log_info "AtlasOS - Calypso Monitoring API Testing"
    log_info "=========================================="
    log_info ""
    
    # Test 1: Enhanced Health Check
    log_info "Test 1: Enhanced Health Check"
    if test_endpoint "GET" "/api/v1/health" "" "Enhanced health check" false; then
        log_success "Health check endpoint working"
    else
        log_error "Health check failed. Is the API running?"
        exit 1
    fi
    echo ""
    
    # Test 2: Login (if needed)
    if [ ! -f "$TOKEN_FILE" ]; then
        log_info "Test 2: User Login"
        login_data="{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASS\"}"
        response=$(curl -s -X POST "$API_URL/api/v1/auth/login" \
            -H "Content-Type: application/json" \
            -d "$login_data")
        
        token=$(echo "$response" | jq -r '.token' 2>/dev/null)
        if [ -n "$token" ] && [ "$token" != "null" ]; then
            echo "$token" > "$TOKEN_FILE"
            log_success "Login successful"
        else
            log_error "Login failed"
            echo "$response" | jq . 2>/dev/null || echo "$response"
            log_warn "Note: You may need to create the admin user in the database first"
            exit 1
        fi
        echo ""
    else
        log_info "Using existing authentication token"
        echo ""
    fi
    
    # Test 3: List Alerts
    log_info "Test 3: List Alerts"
    test_endpoint "GET" "/api/v1/monitoring/alerts" "" "List all alerts"
    echo ""
    
    # Test 4: List Alerts with Filters
    log_info "Test 4: List Alerts (Critical Only)"
    test_endpoint "GET" "/api/v1/monitoring/alerts?severity=critical&limit=10" "" "List critical alerts"
    echo ""
    
    # Test 5: Get Metrics
    log_info "Test 5: Get System Metrics"
    test_endpoint "GET" "/api/v1/monitoring/metrics" "" "Get system metrics"
    echo ""
    
    # Test 6: Create a Test Alert (if we can trigger one)
    log_info "Test 6: Check for Active Alerts"
    alerts_response=$(curl -s -X GET "$API_URL/api/v1/monitoring/alerts?limit=1" \
        -H "Content-Type: application/json" \
        -H "Authorization: Bearer $(cat $TOKEN_FILE)")
    
    alert_id=$(echo "$alerts_response" | jq -r '.alerts[0].id' 2>/dev/null)
    if [ -n "$alert_id" ] && [ "$alert_id" != "null" ]; then
        log_success "Found alert: $alert_id"
        
        # Test 7: Get Single Alert
        log_info "Test 7: Get Alert Details"
        test_endpoint "GET" "/api/v1/monitoring/alerts/$alert_id" "" "Get alert details"
        echo ""
        
        # Test 8: Acknowledge Alert (if not already acknowledged)
        is_acknowledged=$(echo "$alerts_response" | jq -r '.alerts[0].is_acknowledged' 2>/dev/null)
        if [ "$is_acknowledged" = "false" ]; then
            log_info "Test 8: Acknowledge Alert"
            test_endpoint "POST" "/api/v1/monitoring/alerts/$alert_id/acknowledge" "" "Acknowledge alert"
            echo ""
        else
            log_warn "Test 8: Alert already acknowledged, skipping"
            echo ""
        fi
        
        # Test 9: Resolve Alert
        log_info "Test 9: Resolve Alert"
        test_endpoint "POST" "/api/v1/monitoring/alerts/$alert_id/resolve" "" "Resolve alert"
        echo ""
    else
        log_warn "No alerts found. Alert rules will generate alerts when conditions are met."
        log_warn "You can wait for storage capacity alerts or task failure alerts."
        echo ""
    fi
    
    # Test 10: WebSocket Connection Test (basic)
    log_info "Test 10: WebSocket Connection Test"
    log_warn "WebSocket testing requires a WebSocket client."
    log_info "You can test WebSocket connections using:"
    log_info "  - Browser: new WebSocket('ws://localhost:8080/api/v1/monitoring/events')"
    log_info "  - wscat: wscat -c ws://localhost:8080/api/v1/monitoring/events"
    log_info "  - curl (with --include): curl --include --no-buffer --header 'Connection: Upgrade' --header 'Upgrade: websocket' --header 'Sec-WebSocket-Key: test' --header 'Sec-WebSocket-Version: 13' http://localhost:8080/api/v1/monitoring/events"
    echo ""
    
    # Summary
    log_info "=========================================="
    log_info "Monitoring API Test Summary"
    log_info "=========================================="
    log_success "Enhanced Monitoring endpoints are operational!"
    log_info ""
    log_info "Available Endpoints:"
    log_info "  - GET  /api/v1/health (enhanced)"
    log_info "  - GET  /api/v1/monitoring/alerts"
    log_info "  - GET  /api/v1/monitoring/alerts/:id"
    log_info "  - POST /api/v1/monitoring/alerts/:id/acknowledge"
    log_info "  - POST /api/v1/monitoring/alerts/:id/resolve"
    log_info "  - GET  /api/v1/monitoring/metrics"
    log_info "  - GET  /api/v1/monitoring/events (WebSocket)"
    log_info ""
    log_info "Alert Rules Active:"
    log_info "  - Storage Capacity Warning (80%)"
    log_info "  - Storage Capacity Critical (95%)"
    log_info "  - Task Failure (60 min lookback)"
    log_info ""
}

# Run tests
main "$@"

