#!/bin/bash

# 53-Suite NPX Client Test Script
# Comprehensive end-to-end testing

set -e

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

echo -e "${YELLOW}=========================================${NC}"
echo -e "${YELLOW}53-SUITE NPX CLIENT TEST SUITE${NC}"
echo -e "${YELLOW}=========================================${NC}"
echo ""

# Test counters
PASSED=0
FAILED=0

# Test function
run_test() {
    local test_name="$1"
    local command="$2"
    local expected_check="$3"
    
    echo -n "Testing: $test_name ... "
    
    if result=$(eval "$command" 2>/dev/null); then
        if [ -n "$expected_check" ] && ! eval "$expected_check"; then
            echo -e "${RED}✗ FAILED${NC} (unexpected result)"
            ((FAILED++))
            return 1
        fi
        echo -e "${GREEN}✓ PASSED${NC}"
        ((PASSED++))
    else
        echo -e "${RED}✗ FAILED${NC} (command failed)"
        ((FAILED++))
        return 1
    fi
}

# 1. CONNECTION TEST
echo -e "${YELLOW}1. CONNECTION TEST${NC}"
echo "-------------------"
run_test "Service health check" \
    "curl -s https://53-suite-mcp-server-production.up.railway.app/health | jq '.status' | grep -q 'healthy'" \
    ""

# 2. CLIENT STARTUP TEST
echo ""
echo -e "${YELLOW}2. CLIENT STARTUP TEST${NC}"
echo "----------------------"
run_test "Client startup and tool listing" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"id\":1}' | node dist/index.js 2>/dev/null | jq '.result.tools | length'" \
    '[ "$result" -eq "16" ]'

# 3. BASIC TOOL TESTS
echo ""
echo -e "${YELLOW}3. BASIC TOOL TESTS${NC}"
echo "-------------------"

run_test "list_sp53_control_families" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"list_sp53_control_families\",\"arguments\":{}},\"id\":2}' | node dist/index.js 2>/dev/null | jq '.result.content[0].text | fromjson | .total_families'" \
    '[ "$result" -eq "20" ]'

run_test "get_sp53_family (AC)" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"get_sp53_family\",\"arguments\":{\"family_id\":\"AC\"}},\"id\":3}' | node dist/index.js 2>/dev/null | jq '.result.content[0].text | fromjson | .family.element_identifier' | tr -d '\"'" \
    '[ "$result" = "AC" ]'

run_test "get_sp53_control (AC-02)" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"get_sp53_control\",\"arguments\":{\"control_id\":\"AC-02\"}},\"id\":4}' | node dist/index.js 2>/dev/null | jq '.result.content[0].text | fromjson | .control.id' | tr -d '\"'" \
    '[ "$result" = "AC-02" ]'

run_test "search_sp53_controls" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"search_sp53_controls\",\"arguments\":{\"keyword\":\"access\",\"limit\":3}},\"id\":5}' | node dist/index.js 2>/dev/null | jq '.result.content[0].text | fromjson | .query' | tr -d '\"'" \
    '[ "$result" = "access" ]'

# 4. ENHANCED TOOL TESTS
echo ""
echo -e "${YELLOW}4. ENHANCED TOOL TESTS${NC}"
echo "----------------------"

run_test "generate_sp53_assessment_plan" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"generate_sp53_assessment_plan\",\"arguments\":{\"control_ids\":[\"AC-02\",\"AC-03\"]}},\"id\":6}' | node dist/index.js 2>/dev/null | jq '.result.content[0].text | fromjson | .assessment_plan.controls | length'" \
    '[ "$result" -eq "2" ]'

run_test "analyze_sp53_control_overlay" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"analyze_sp53_control_overlay\",\"arguments\":{\"baseline\":\"moderate\",\"system_type\":\"cloud\",\"data_types\":[\"pii\"]}},\"id\":7}' | node dist/index.js 2>/dev/null | jq '.result.content[0].text | fromjson | .overlay_analysis.baseline' | tr -d '\"'" \
    '[ "$result" = "moderate" ]'

# 5. ERROR HANDLING TESTS
echo ""
echo -e "${YELLOW}5. ERROR HANDLING TESTS${NC}"
echo "-----------------------"

run_test "Invalid control ID" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"get_sp53_control\",\"arguments\":{\"control_id\":\"INVALID-999\"}},\"id\":8}' | node dist/index.js 2>/dev/null | jq '.result.content[0].text'" \
    'echo "$result" | grep -q "not found"'

run_test "Missing required parameter" \
    "echo '{\"jsonrpc\":\"2.0\",\"method\":\"tools/call\",\"params\":{\"name\":\"get_sp53_control\",\"arguments\":{}},\"id\":9}' | node dist/index.js 2>/dev/null" \
    'echo "$result" | grep -q "Required"'

# 6. PERFORMANCE TEST
echo ""
echo -e "${YELLOW}6. PERFORMANCE TEST${NC}"
echo "-------------------"
echo -n "Testing: Response time (tool listing) ... "
start_time=$(date +%s%N)
echo '{"jsonrpc":"2.0","method":"tools/list","id":1}' | node dist/index.js 2>/dev/null >/dev/null
end_time=$(date +%s%N)
duration=$(( (end_time - start_time) / 1000000 )) # Convert to milliseconds

if [ $duration -lt 2000 ]; then # Less than 2 seconds
    echo -e "${GREEN}✓ PASSED${NC} (${duration}ms)"
    ((PASSED++))
else
    echo -e "${RED}✗ FAILED${NC} (${duration}ms - too slow)"
    ((FAILED++))
fi

# Final results
echo ""
echo -e "${YELLOW}=========================================${NC}"
echo -e "${YELLOW}TEST RESULTS${NC}"
echo -e "${YELLOW}=========================================${NC}"
echo -e "Passed: ${GREEN}$PASSED${NC}"
echo -e "Failed: ${RED}$FAILED${NC}"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✓ ALL TESTS PASSED!${NC}"
    echo ""
    echo "🚀 The 53-suite NPX client is ready for deployment!"
    echo "   • Railway service: ✓ Running"
    echo "   • Client connectivity: ✓ Working"
    echo "   • All 16 tools: ✓ Functional"
    echo "   • Error handling: ✓ Proper"
    echo "   • Performance: ✓ Acceptable"
    echo ""
    echo "Next steps:"
    echo "1. Publish to NPM: npm publish"
    echo "2. Test with Claude Desktop"
    echo "3. Update documentation"
    exit 0
else
    echo -e "${RED}⚠ SOME TESTS FAILED${NC}"
    exit 1
fi