#!/bin/bash

# Comprehensive Bot Management Testing Script for LittleShop
# Tests all bot functionality end-to-end

set -e

HOST="10.0.0.11:5000"
COOKIES_FILE="test-cookies.txt"

echo "🧪 Starting comprehensive bot management tests..."

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

# Helper function for test results
test_result() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✅ PASS${NC}: $2"
    else
        echo -e "${RED}❌ FAIL${NC}: $2"
        exit 1
    fi
}

# Cleanup function
cleanup() {
    rm -f $COOKIES_FILE response.html response.json
}
trap cleanup EXIT

echo -e "${YELLOW}🔐 Test 1: Admin Authentication${NC}"
# Test admin login
curl -c $COOKIES_FILE -s -X POST \
    -d "username=admin&password=admin" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    http://$HOST/Admin/Account/Login > /dev/null

# Check if we got authentication cookie
if grep -q "AspNetCore.Cookies" $COOKIES_FILE; then
    test_result 0 "Admin login successful"
else
    test_result 1 "Admin login failed"
fi

echo -e "${YELLOW}🤖 Test 2: Bot List Access${NC}"
# Test bot list page
HTTP_CODE=$(curl -b $COOKIES_FILE -s -w "%{http_code}" -o response.html http://$HOST/Admin/Bots)
if [ "$HTTP_CODE" = "200" ]; then
    test_result 0 "Bot list page accessible"
else
    test_result 1 "Bot list page failed (HTTP $HTTP_CODE)"
fi

echo -e "${YELLOW}📝 Test 3: Bot Registration Form${NC}"
# Test bot registration form
curl -c $COOKIES_FILE -b $COOKIES_FILE -s http://$HOST/Admin/Bots/Create > response.html
if grep -q "Register New Bot" response.html && grep -q "__RequestVerificationToken" response.html; then
    test_result 0 "Bot registration form renders correctly"
else
    test_result 1 "Bot registration form has issues"
fi

echo -e "${YELLOW}🚀 Test 4: Bot Registration${NC}"
# Extract anti-forgery token
TOKEN=$(grep -o 'name="__RequestVerificationToken"[^>]*value="[^"]*"' response.html | sed 's/.*value="//' | sed 's/".*//')

# Register a new test bot
BOT_NAME="TestBot_$(date +%s)"
HTTP_CODE=$(curl -b $COOKIES_FILE -s -X POST \
    -d "__RequestVerificationToken=$TOKEN&Name=$BOT_NAME&Description=Automated test bot&Type=0&Version=1.0.0" \
    -H "Content-Type: application/x-www-form-urlencoded" \
    -w "%{http_code}" -o response.html -L \
    http://$HOST/Admin/Bots/Create)

if [ "$HTTP_CODE" = "200" ] && grep -q "API key" response.html; then
    # Extract API key from response
    API_KEY=$(grep -o 'bot_[A-Za-z0-9]*' response.html | head -1)
    test_result 0 "Bot registration successful (API Key: $API_KEY)"
else
    test_result 1 "Bot registration failed (HTTP $HTTP_CODE)"
fi

echo -e "${YELLOW}🔑 Test 5: Bot API Authentication${NC}"
# Test bot authentication via API
RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" \
    -d "{\"BotKey\":\"$API_KEY\"}" \
    http://$HOST/api/bots/authenticate)

if echo "$RESPONSE" | grep -q '"name":"'$BOT_NAME'"'; then
    BOT_ID=$(echo "$RESPONSE" | grep -o '"id":"[^"]*"' | sed 's/"id":"//' | sed 's/"//')
    test_result 0 "Bot API authentication successful (Bot ID: $BOT_ID)"
else
    test_result 1 "Bot API authentication failed"
fi

echo -e "${YELLOW}⚙️ Test 6: Bot Settings API${NC}"
# Test getting bot settings
SETTINGS_RESPONSE=$(curl -s -H "X-Bot-Key: $API_KEY" http://$HOST/api/bots/settings)
if [ "$SETTINGS_RESPONSE" = "{}" ]; then
    test_result 0 "Bot settings API working"
else
    test_result 1 "Bot settings API failed"
fi

echo -e "${YELLOW}📊 Test 7: Metrics Submission${NC}"
# Test metrics submission
METRIC_RESPONSE=$(curl -s -X POST -H "X-Bot-Key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"MetricType":0,"Value":1,"Category":"Test","Description":"Automated test metric"}' \
    http://$HOST/api/bots/metrics)

if echo "$METRIC_RESPONSE" | grep -q '"metricType":0'; then
    test_result 0 "Metrics submission successful"
else
    test_result 1 "Metrics submission failed"
fi

echo -e "${YELLOW}📱 Test 8: Session Management${NC}"
# Test session creation
SESSION_RESPONSE=$(curl -s -X POST -H "X-Bot-Key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"SessionIdentifier":"test_session_456","Platform":"Telegram","Language":"en","Country":"UK","IsAnonymous":true}' \
    http://$HOST/api/bots/sessions/start)

if echo "$SESSION_RESPONSE" | grep -q '"sessionIdentifier":"test_session_456"'; then
    SESSION_ID=$(echo "$SESSION_RESPONSE" | grep -o '"id":"[^"]*"' | sed 's/"id":"//' | sed 's/"//')
    test_result 0 "Session creation successful (Session ID: $SESSION_ID)"
else
    test_result 1 "Session creation failed"
fi

echo -e "${YELLOW}💓 Test 9: Heartbeat${NC}"
# Test heartbeat
curl -s -X POST -H "X-Bot-Key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"Version":"1.0.0","IpAddress":"127.0.0.1","ActiveSessions":1,"Status":{"healthy":true}}' \
    http://$HOST/api/bots/heartbeat > /dev/null

# Check if heartbeat was recorded (bot should show as recently seen)
RECENT_RESPONSE=$(curl -s -X POST -H "Content-Type: application/json" \
    -d "{\"BotKey\":\"$API_KEY\"}" \
    http://$HOST/api/bots/authenticate)

if echo "$RECENT_RESPONSE" | grep -q '"lastSeenAt"'; then
    test_result 0 "Heartbeat submission successful"
else
    test_result 1 "Heartbeat submission failed"
fi

echo -e "${YELLOW}📈 Test 10: Admin Metrics View${NC}"
# Test admin metrics view
HTTP_CODE=$(curl -b $COOKIES_FILE -s -w "%{http_code}" -o response.html "http://$HOST/Admin/Bots/Metrics/$BOT_ID")
if [ "$HTTP_CODE" = "200" ] && grep -q "Bot Metrics" response.html; then
    test_result 0 "Admin metrics view accessible"
else
    test_result 1 "Admin metrics view failed (HTTP $HTTP_CODE)"
fi

echo -e "${YELLOW}🔧 Test 11: Bot Settings Update${NC}"
# Test updating bot settings
SETTINGS_UPDATE='{"Settings":{"telegram":{"botToken":"test_token"},"privacy":{"mode":"strict"}}}'
HTTP_CODE=$(curl -s -X PUT -H "X-Bot-Key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d "$SETTINGS_UPDATE" \
    -w "%{http_code}" -o /dev/null \
    http://$HOST/api/bots/settings)

if [ "$HTTP_CODE" = "204" ]; then
    test_result 0 "Bot settings update successful"
else
    test_result 1 "Bot settings update failed (HTTP $HTTP_CODE)"
fi

echo -e "${YELLOW}📊 Test 12: Batch Metrics${NC}"
# Test batch metrics submission
BATCH_METRICS='{"Metrics":[{"MetricType":4,"Value":5,"Category":"Messages","Description":"Message count"},{"MetricType":2,"Value":1,"Category":"Orders","Description":"Order placed"}]}'
HTTP_CODE=$(curl -s -X POST -H "X-Bot-Key: $API_KEY" \
    -H "Content-Type: application/json" \
    -d "$BATCH_METRICS" \
    -w "%{http_code}" -o /dev/null \
    http://$HOST/api/bots/metrics/batch)

if [ "$HTTP_CODE" = "200" ]; then
    test_result 0 "Batch metrics submission successful"
else
    test_result 1 "Batch metrics submission failed (HTTP $HTTP_CODE)"
fi

echo ""
echo -e "${GREEN}🎉 ALL TESTS PASSED!${NC}"
echo -e "${GREEN}✅ Bot Management System is fully functional${NC}"
echo ""
echo "Summary:"
echo "- Bot Name: $BOT_NAME"
echo "- Bot ID: $BOT_ID"
echo "- API Key: $API_KEY"
echo "- Session ID: $SESSION_ID"
echo ""
echo "The bot management system is ready for production use!"
echo "Users can now:"
echo "1. Register bots through the admin panel"
echo "2. Manage bot settings centrally"
echo "3. Monitor bot metrics and sessions"
echo "4. Use API keys for bot authentication"