#!/bin/bash
# Monitor RPC Endpoint - Basic monitoring script
# Usage: ./scripts/monitor-rpc-endpoint.sh [interval_seconds]

set -e

RPC_URL="${RPC_URL:-https://rpc.public-0138.defi-oracle.io}"
INTERVAL="${1:-60}"  # Default 60 seconds
LOG_FILE="${LOG_FILE:-/tmp/rpc-monitor.log}"

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

# Statistics
TOTAL_REQUESTS=0
SUCCESSFUL_REQUESTS=0
FAILED_REQUESTS=0
TOTAL_RESPONSE_TIME=0
MIN_RESPONSE_TIME=999999
MAX_RESPONSE_TIME=0

# Function to make RPC request
make_request() {
    local start_time=$(date +%s.%N)
    local response=$(curl -s --max-time 10 -w "\nHTTP_CODE:%{http_code}\nTIME:%{time_total}" \
        -X POST "$RPC_URL" \
        -H 'Content-Type: application/json' \
        -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' 2>&1)
    local end_time=$(date +%s.%N)
    local response_time=$(echo "$end_time - $start_time" | bc)
    
    echo "$response|$response_time"
}

# Function to check endpoint
check_endpoint() {
    local result=$(make_request)
    local response=$(echo "$result" | grep -v "HTTP_CODE\|TIME" | head -1)
    local http_code=$(echo "$result" | grep "HTTP_CODE" | cut -d: -f2)
    local curl_time=$(echo "$result" | grep "TIME" | cut -d: -f2)
    
    TOTAL_REQUESTS=$((TOTAL_REQUESTS + 1))
    
    if [ "$http_code" = "200" ] && echo "$response" | grep -q '"result":"0x8a"'; then
        SUCCESSFUL_REQUESTS=$((SUCCESSFUL_REQUESTS + 1))
        local success_rate=$(echo "scale=2; $SUCCESSFUL_REQUESTS * 100 / $TOTAL_REQUESTS" | bc)
        echo -e "${GREEN}✅ Success${NC} (HTTP $http_code, ${curl_time}s, Success rate: ${success_rate}%)"
        echo "$(date -u +"%Y-%m-%d %H:%M:%S UTC"),SUCCESS,$http_code,$curl_time" >> "$LOG_FILE"
    else
        FAILED_REQUESTS=$((FAILED_REQUESTS + 1))
        local success_rate=$(echo "scale=2; $SUCCESSFUL_REQUESTS * 100 / $TOTAL_REQUESTS" | bc)
        echo -e "${RED}❌ Failed${NC} (HTTP ${http_code:-N/A}, ${curl_time}s, Success rate: ${success_rate}%)"
        echo "$(date -u +"%Y-%m-%d %H:%M:%S UTC"),FAILED,${http_code:-N/A},$curl_time" >> "$LOG_FILE"
        
        # Alert if success rate drops below 70%
        if (( $(echo "$success_rate < 70" | bc -l) )); then
            echo -e "${YELLOW}⚠️  WARNING: Success rate below 70%!${NC}"
        fi
    fi
    
    # Update response time stats
    local time_ms=$(echo "$curl_time * 1000" | bc | cut -d. -f1)
    TOTAL_RESPONSE_TIME=$(echo "$TOTAL_RESPONSE_TIME + $time_ms" | bc)
    if [ "$time_ms" -lt "$MIN_RESPONSE_TIME" ]; then
        MIN_RESPONSE_TIME=$time_ms
    fi
    if [ "$time_ms" -gt "$MAX_RESPONSE_TIME" ]; then
        MAX_RESPONSE_TIME=$time_ms
    fi
}

# Function to print statistics
print_stats() {
    if [ $TOTAL_REQUESTS -eq 0 ]; then
        return
    fi
    
    local success_rate=$(echo "scale=2; $SUCCESSFUL_REQUESTS * 100 / $TOTAL_REQUESTS" | bc)
    local avg_time=$(echo "scale=2; $TOTAL_RESPONSE_TIME / $TOTAL_REQUESTS" | bc)
    local avg_time_sec=$(echo "scale=3; $avg_time / 1000" | bc)
    
    echo ""
    echo "=== Statistics ==="
    echo "Total Requests: $TOTAL_REQUESTS"
    echo "Successful: $SUCCESSFUL_REQUESTS"
    echo "Failed: $FAILED_REQUESTS"
    echo "Success Rate: ${success_rate}%"
    echo "Avg Response Time: ${avg_time_sec}s (${avg_time}ms)"
    echo "Min Response Time: $(echo "scale=3; $MIN_RESPONSE_TIME / 1000" | bc)s ($MIN_RESPONSE_TIME ms)"
    echo "Max Response Time: $(echo "scale=3; $MAX_RESPONSE_TIME / 1000" | bc)s ($MAX_RESPONSE_TIME ms)"
    echo "=================="
    echo ""
}

# Trap to print stats on exit
trap print_stats EXIT INT TERM

# Initialize log file
echo "timestamp,status,http_code,response_time_seconds" > "$LOG_FILE"

echo "Starting RPC Endpoint Monitor"
echo "RPC URL: $RPC_URL"
echo "Interval: $INTERVAL seconds"
echo "Log File: $LOG_FILE"
echo "Press Ctrl+C to stop"
echo ""

# Main monitoring loop
while true; do
    check_endpoint
    sleep "$INTERVAL"
done
