#!/bin/bash

################################################################################
# Railway Internal Networking Test Runner
#
# Purpose: Run 100 consecutive HTTP requests to validate Railway internal
#          networking between services for bot-spawner extraction.
#
# Usage:
#   ./test-runner.sh [SERVICE_URL]
#
# Examples:
#   # Test using Railway internal networking
#   ./test-runner.sh http://test-service-a.railway.internal:3000
#
#   # Test using public URL
#   ./test-runner.sh https://test-service-a.railway.app
#
# Output:
#   - results.json: Array of test results with status, latency, timestamp
#   - Console: Progress updates for each request
#
# Requirements:
#   - curl must be installed
#   - jq is optional but recommended for pretty-printing
#
################################################################################

set -e  # Exit on error
set -u  # Exit on undefined variable

# Configuration
SERVICE_URL="${1:-https://test-service-a.railway.app}"
OUTPUT_FILE="results.json"
TEMP_FILE="results.json.tmp"
TOTAL_REQUESTS=100

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

# Cleanup function
cleanup() {
    if [ -f "$TEMP_FILE" ]; then
        rm -f "$TEMP_FILE"
    fi
}
trap cleanup EXIT

# Print usage
print_usage() {
    echo "Usage: $0 [SERVICE_URL]"
    echo ""
    echo "Arguments:"
    echo "  SERVICE_URL  URL of test service (default: https://test-service-a.railway.app)"
    echo ""
    echo "Examples:"
    echo "  $0 http://test-service-a.railway.internal:3000"
    echo "  $0 https://test-service-a.railway.app"
}

# Validate curl is installed
if ! command -v curl &> /dev/null; then
    echo -e "${RED}Error: curl is not installed${NC}"
    echo "Please install curl to run this script"
    exit 1
fi

# Print header
echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  Railway Internal Networking Test Runner                      ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "Configuration:"
echo "  Service URL:    $SERVICE_URL"
echo "  Total Requests: $TOTAL_REQUESTS"
echo "  Output File:    $OUTPUT_FILE"
echo ""
echo "Starting test run..."
echo ""

# Initialize results file
echo "[" > "$OUTPUT_FILE"

# Track statistics
successful_requests=0
failed_requests=0
start_time=$(date +%s)

# Run requests
for i in $(seq 1 $TOTAL_REQUESTS); do
    # Calculate progress
    progress=$((i * 100 / TOTAL_REQUESTS))

    # Record request start time
    request_start=$(date +%s%3N)  # milliseconds

    # Make request with timing
    http_code=$(curl -s -o /dev/null -w "%{http_code}" \
                     --max-time 10 \
                     --write-out "%{time_total}" \
                     "$SERVICE_URL/test-call" 2>/dev/null || echo "000")

    # Record request end time
    request_end=$(date +%s%3N)  # milliseconds

    # Calculate latency in milliseconds
    latency=$((request_end - request_start))

    # Get current timestamp in ISO format
    timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")

    # Determine if successful
    if [ "$http_code" = "200" ]; then
        successful_requests=$((successful_requests + 1))
        status_color=$GREEN
        status_symbol="✓"
    else
        failed_requests=$((failed_requests + 1))
        status_color=$RED
        status_symbol="✗"
    fi

    # Print progress
    printf "${status_color}[%3d/%3d]${NC} %s Request #%d - Status: %s - Latency: %dms - Progress: %d%%\n" \
           "$i" "$TOTAL_REQUESTS" "$status_symbol" "$i" "$http_code" "$latency" "$progress"

    # Write result to JSON file
    # Note: We'll clean up the trailing comma later
    cat >> "$OUTPUT_FILE" << EOF
  {
    "request_number": $i,
    "status": $http_code,
    "latency": $latency,
    "timestamp": "$timestamp",
    "success": $([ "$http_code" = "200" ] && echo "true" || echo "false")
  },
EOF
done

# Remove trailing comma from last entry and close JSON array
sed -i.bak '$ s/,$//' "$OUTPUT_FILE"
echo "]" >> "$OUTPUT_FILE"
rm -f "${OUTPUT_FILE}.bak"

# Calculate total duration
end_time=$(date +%s)
total_duration=$((end_time - start_time))

# Print summary
echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║  Test Run Complete                                             ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""
echo "Summary:"
echo "  Total Requests:      $TOTAL_REQUESTS"
echo "  Successful:          ${GREEN}$successful_requests${NC}"
echo "  Failed:              ${RED}$failed_requests${NC}"
echo "  Success Rate:        $(awk "BEGIN {printf \"%.2f%%\", ($successful_requests / $TOTAL_REQUESTS) * 100}")"
echo "  Total Duration:      ${total_duration}s"
echo ""
echo "Results saved to: $OUTPUT_FILE"
echo ""

# Suggest next step
if command -v node &> /dev/null && [ -f "analyze-results.ts" ]; then
    echo "Next step: Run the analyzer to get detailed metrics"
    echo "  ${YELLOW}npx tsx analyze-results.ts${NC}"
    echo ""
elif command -v jq &> /dev/null; then
    echo "Preview results with jq:"
    echo "  ${YELLOW}jq '.' $OUTPUT_FILE${NC}"
    echo ""
fi

# Exit with appropriate code
if [ $failed_requests -gt 0 ]; then
    exit 1
else
    exit 0
fi
