#!/bin/bash
# End-to-End Test Script for Token Estimation Feature
# Tests WordPress plugin + Backend API integration

set -e

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

# Configuration
API_URL="${API_URL:-http://localhost:3000}"
API_KEY="${API_KEY:-}"

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Token Estimation E2E Test Suite${NC}"
echo -e "${BLUE}========================================${NC}\n"

# Check if API key is provided
if [ -z "$API_KEY" ]; then
    echo -e "${YELLOW}⚠️  Warning: API_KEY not set. Some tests may fail.${NC}"
    echo -e "${YELLOW}   Set it with: export API_KEY=your_api_key${NC}\n"
fi

# Test counter
TESTS_PASSED=0
TESTS_FAILED=0

# Helper functions
test_passed() {
    echo -e "${GREEN}✓ $1${NC}"
    ((TESTS_PASSED++))
}

test_failed() {
    echo -e "${RED}✗ $1${NC}"
    echo -e "${RED}  Error: $2${NC}"
    ((TESTS_FAILED++))
}

test_section() {
    echo -e "\n${BLUE}━━━ $1 ━━━${NC}\n"
}

# ============================================================================
# Test 1: Database Tables Exist
# ============================================================================

test_section "Test 1: Database Tables"

echo "Checking if translation_records table exists..."
RESULT=$(cd ../backend-app/api && npx prisma db execute --stdin <<EOF
SELECT table_name FROM information_schema.tables 
WHERE table_name = 'translation_records';
EOF
)

if echo "$RESULT" | grep -q "translation_records"; then
    test_passed "translation_records table exists"
else
    test_failed "translation_records table missing" "Table not found in database"
fi

echo "Checking if accuracy_stats table exists..."
RESULT=$(cd ../backend-app/api && npx prisma db execute --stdin <<EOF
SELECT table_name FROM information_schema.tables 
WHERE table_name = 'accuracy_stats';
EOF
)

if echo "$RESULT" | grep -q "accuracy_stats"; then
    test_passed "accuracy_stats table exists"
else
    test_failed "accuracy_stats table missing" "Table not found in database"
fi

# ============================================================================
# Test 2: Backend API - /v1/estimate Endpoint
# ============================================================================

test_section "Test 2: Backend API - Token Estimation"

if [ -z "$API_KEY" ]; then
    echo -e "${YELLOW}⚠️  Skipping API tests (no API_KEY)${NC}"
else
    echo "Testing POST /v1/estimate endpoint..."
    
    RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" -X POST "$API_URL/v1/estimate" \
        -H "Content-Type: application/json" \
        -H "X-API-Key: $API_KEY" \
        -d '{
            "content": "<p>Hello, this is a test translation content with some HTML tags.</p>",
            "source_lang": "en",
            "target_langs": ["es", "fr", "de"]
        }')
    
    HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE" | cut -d: -f2)
    BODY=$(echo "$RESPONSE" | sed '/HTTP_CODE/d')
    
    if [ "$HTTP_CODE" = "200" ]; then
        test_passed "/v1/estimate returns 200 OK"
        
        # Check response structure
        if echo "$BODY" | jq -e '.success' > /dev/null 2>&1; then
            test_passed "Response contains 'success' field"
        else
            test_failed "Response structure invalid" "Missing 'success' field"
        fi
        
        if echo "$BODY" | jq -e '.estimates' > /dev/null 2>&1; then
            test_passed "Response contains 'estimates' field"
            
            # Check individual language estimates
            if echo "$BODY" | jq -e '.estimates.es' > /dev/null 2>&1; then
                test_passed "Spanish (es) estimate present"
            fi
            if echo "$BODY" | jq -e '.estimates.fr' > /dev/null 2>&1; then
                test_passed "French (fr) estimate present"
            fi
            if echo "$BODY" | jq -e '.estimates.de' > /dev/null 2>&1; then
                test_passed "German (de) estimate present"
            fi
        else
            test_failed "Response structure invalid" "Missing 'estimates' field"
        fi
        
        if echo "$BODY" | jq -e '.total_tokens' > /dev/null 2>&1; then
            TOTAL_TOKENS=$(echo "$BODY" | jq -r '.total_tokens')
            test_passed "Total tokens calculated: $TOTAL_TOKENS"
        else
            test_failed "Response structure invalid" "Missing 'total_tokens' field"
        fi
        
        echo -e "\n${BLUE}Response:${NC}"
        echo "$BODY" | jq '.'
    else
        test_failed "/v1/estimate endpoint failed" "HTTP $HTTP_CODE"
        echo "$BODY"
    fi
fi

# ============================================================================
# Test 3: Backend API - /v1/stats/accuracy Endpoint
# ============================================================================

test_section "Test 3: Backend API - Accuracy Statistics"

if [ -z "$API_KEY" ]; then
    echo -e "${YELLOW}⚠️  Skipping API tests (no API_KEY)${NC}"
else
    echo "Testing GET /v1/stats/accuracy endpoint..."
    
    RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" -X GET "$API_URL/v1/stats/accuracy" \
        -H "X-API-Key: $API_KEY")
    
    HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE" | cut -d: -f2)
    BODY=$(echo "$RESPONSE" | sed '/HTTP_CODE/d')
    
    if [ "$HTTP_CODE" = "200" ]; then
        test_passed "/v1/stats/accuracy returns 200 OK"
        
        if echo "$BODY" | jq -e '.success' > /dev/null 2>&1; then
            test_passed "Response contains 'success' field"
        fi
        
        if echo "$BODY" | jq -e '.stats' > /dev/null 2>&1; then
            test_passed "Response contains 'stats' array"
            LANG_COUNT=$(echo "$BODY" | jq -r '.total_languages')
            echo -e "  ${BLUE}→ Languages with training data: $LANG_COUNT${NC}"
        fi
        
        echo -e "\n${BLUE}Response:${NC}"
        echo "$BODY" | jq '.'
    else
        test_failed "/v1/stats/accuracy endpoint failed" "HTTP $HTTP_CODE"
    fi
fi

# ============================================================================
# Test 4: WordPress Plugin Files
# ============================================================================

test_section "Test 4: WordPress Plugin Files"

echo "Checking if TokenEstimator class exists..."
if [ -f "includes/class-tpz-tokenestimator.php" ]; then
    test_passed "TokenEstimator PHP class exists"
    
    # Check for key methods
    if grep -q "estimate_batch" includes/class-tpz-tokenestimator.php; then
        test_passed "estimate_batch() method found"
    fi
    if grep -q "check_credits" includes/class-tpz-tokenestimator.php; then
        test_passed "check_credits() method found"
    fi
else
    test_failed "TokenEstimator class missing" "File not found"
fi

echo "Checking if AJAX handler exists..."
if [ -f "includes/class-tpz-metabox.php" ]; then
    if grep -q "ajax_estimate_tokens" includes/class-tpz-metabox.php; then
        test_passed "ajax_estimate_tokens() handler found"
    else
        test_failed "AJAX handler missing" "Method not found in Metabox class"
    fi
fi

echo "Checking JavaScript files..."
if [ -f "admin/js/metabox.js" ]; then
    if grep -q "updateTokenEstimate" admin/js/metabox.js; then
        test_passed "updateTokenEstimate() function found in metabox.js"
    fi
fi

if [ -f "admin/js/dashboard.js" ]; then
    if grep -q "formatTokens" admin/js/dashboard.js; then
        test_passed "formatTokens() function found in dashboard.js"
    fi
fi

# ============================================================================
# Test 5: Backend Services
# ============================================================================

test_section "Test 5: Backend Services"

echo "Checking if TokenEstimator service exists..."
if [ -f "backend-app/api/src/services/TokenEstimator.ts" ]; then
    test_passed "TokenEstimator.ts service exists"
    
    if grep -q "estimateBatch" backend-app/api/src/services/TokenEstimator.ts; then
        test_passed "estimateBatch() method found"
    fi
    if grep -q "getLanguageFactor" backend-app/api/src/services/TokenEstimator.ts; then
        test_passed "getLanguageFactor() method found"
    fi
else
    test_failed "TokenEstimator service missing" "File not found"
fi

echo "Checking if AccuracyTracker service exists..."
if [ -f "backend-app/api/src/services/AccuracyTracker.ts" ]; then
    test_passed "AccuracyTracker.ts service exists"
    
    if grep -q "recordUsage" backend-app/api/src/services/AccuracyTracker.ts; then
        test_passed "recordUsage() method found"
    fi
    if grep -q "updateMLAdjustment" backend-app/api/src/services/AccuracyTracker.ts; then
        test_passed "updateMLAdjustment() method found"
    fi
else
    test_failed "AccuracyTracker service missing" "File not found"
fi

echo "Checking if routes are registered..."
if [ -f "backend-app/api/src/routes/estimate.ts" ]; then
    test_passed "estimate.ts route exists"
fi
if [ -f "backend-app/api/src/routes/stats.ts" ]; then
    test_passed "stats.ts route exists"
fi
if grep -q "estimateRoutes" backend-app/api/src/server.ts; then
    test_passed "estimateRoutes registered in server.ts"
fi
if grep -q "statsRoutes" backend-app/api/src/server.ts; then
    test_passed "statsRoutes registered in server.ts"
fi

# ============================================================================
# Test 6: Database Migration
# ============================================================================

test_section "Test 6: Database Migration"

echo "Checking Prisma schema..."
if [ -f "backend-app/api/prisma/schema.prisma" ]; then
    if grep -q "TranslationRecord" backend-app/api/prisma/schema.prisma; then
        test_passed "TranslationRecord model in schema"
    fi
    if grep -q "AccuracyStats" backend-app/api/prisma/schema.prisma; then
        test_passed "AccuracyStats model in schema"
    fi
    if grep -q "HTMLComplexity" backend-app/api/prisma/schema.prisma; then
        test_passed "HTMLComplexity enum in schema"
    fi
fi

# ============================================================================
# Test Results Summary
# ============================================================================

test_section "Test Results Summary"

TOTAL_TESTS=$((TESTS_PASSED + TESTS_FAILED))

echo -e "Total Tests:   ${BLUE}$TOTAL_TESTS${NC}"
echo -e "Passed:        ${GREEN}$TESTS_PASSED${NC}"
echo -e "Failed:        ${RED}$TESTS_FAILED${NC}"
echo ""

if [ $TESTS_FAILED -eq 0 ]; then
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}✓ ALL TESTS PASSED!${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    exit 0
else
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${RED}✗ SOME TESTS FAILED${NC}"
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    exit 1
fi
