#!/usr/bin/env bash
# Update Cloudflare Tunnel Configuration for VMID 2400
# Routes rpc.public-0138.defi-oracle.io to Besu RPC ports directly

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ENV_FILE="$PROJECT_ROOT/.env"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

# Configuration
TUNNEL_ID="26138c21-db00-4a02-95db-ec75c07bda5b"
RPC_HTTP_PORT="8545"
RPC_WS_PORT="8546"

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  UPDATING VMID 2400 TUNNEL CONFIGURATION"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Check for .env file
if [ ! -f "$ENV_FILE" ]; then
    log_error ".env file not found"
    exit 1
fi

source "$ENV_FILE"

# Determine authentication
AUTH_HEADERS=()
if [ -n "${CLOUDFLARE_API_TOKEN:-}" ]; then
    AUTH_HEADERS=(-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN")
elif [ -n "${CLOUDFLARE_API_KEY:-}" ] && [ -n "${CLOUDFLARE_EMAIL:-}" ]; then
    AUTH_HEADERS=(-H "X-Auth-Email: $CLOUDFLARE_EMAIL" -H "X-Auth-Key: $CLOUDFLARE_API_KEY")
else
    log_error "No Cloudflare credentials found"
    exit 1
fi

# Get Account ID
if [ -z "${CLOUDFLARE_ACCOUNT_ID:-}" ]; then
    log_info "Getting Account ID..."
    ACCOUNT_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/accounts" \
        "${AUTH_HEADERS[@]}" \
        -H "Content-Type: application/json")
    CLOUDFLARE_ACCOUNT_ID=$(echo "$ACCOUNT_RESPONSE" | jq -r '.result[0].id // empty')
    
    if [ -z "$CLOUDFLARE_ACCOUNT_ID" ] || [ "$CLOUDFLARE_ACCOUNT_ID" = "null" ]; then
        log_error "Failed to get Account ID"
        exit 1
    fi
fi

log_success "Account ID: $CLOUDFLARE_ACCOUNT_ID"
log_success "Tunnel ID: $TUNNEL_ID"

# Build ingress configuration
log_info "Building tunnel ingress configuration..."
log_info "  HTTP RPC → http://127.0.0.1:${RPC_HTTP_PORT}"
log_info "  WebSocket RPC → ws://127.0.0.1:${RPC_WS_PORT}"

# Note: Cloudflare tunnels handle WebSocket upgrades automatically
# We route HTTP to 8545, and WebSocket will also route there initially
# For WebSocket to route to 8546, we need to use a service that can handle the upgrade
# Since Besu handles both HTTP and WebSocket on different ports, we'll configure
# the tunnel to route HTTP to 8545, and use originRequest to handle WebSocket upgrades

INGRESS_CONFIG=$(jq -n \
    --arg http_port "$RPC_HTTP_PORT" \
    --arg ws_port "$RPC_WS_PORT" \
    '{
        config: {
            ingress: [
                {
                    hostname: "info.defi-oracle.io",
                    service: "http://127.0.0.1:80"
                },
                {
                    hostname: "rpc.public-0138.defi-oracle.io",
                    service: "http://127.0.0.1:\($http_port)",
                    originRequest: {
                        httpHostHeader: "rpc.public-0138.defi-oracle.io",
                        noHappyEyeballs: false
                    }
                },
                {
                    service: "http_status:404"
                }
            ],
            "warp-routing": {
                enabled: false
            }
        }
    }')

log_info "Updating tunnel configuration..."

# Update tunnel configuration
RESPONSE=$(curl -s -X PUT \
    "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/cfd_tunnel/${TUNNEL_ID}/configurations" \
    "${AUTH_HEADERS[@]}" \
    -H "Content-Type: application/json" \
    -d "$INGRESS_CONFIG")

if echo "$RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
    log_success "Tunnel configuration updated successfully!"
    echo ""
    log_info "Configuration will be applied within 1-2 minutes"
else
    log_error "Failed to update tunnel configuration"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
    exit 1
fi

echo ""
log_info "Note: Cloudflare tunnels handle WebSocket upgrades automatically."
log_info "For WebSocket to route to port 8546, you may need Nginx to handle"
log_info "the protocol detection and route accordingly."
echo ""

# Verify configuration
log_info "Verifying tunnel configuration..."
sleep 2
VERIFY_RESPONSE=$(curl -s -X GET \
    "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/cfd_tunnel/${TUNNEL_ID}/configurations" \
    "${AUTH_HEADERS[@]}" \
    -H "Content-Type: application/json")

if echo "$VERIFY_RESPONSE" | jq -e '.success' > /dev/null 2>&1; then
    INGRESS_COUNT=$(echo "$VERIFY_RESPONSE" | jq '.result.config.ingress | length')
    log_success "Configuration verified: $INGRESS_COUNT ingress rules configured"
    
    echo ""
    log_info "Configured hostnames:"
    echo "$VERIFY_RESPONSE" | jq -r '.result.config.ingress[] | select(.hostname != null) | "  - \(.hostname) → \(.service)"'
else
    log_warn "Could not verify configuration (this is normal if tunnel is still updating)"
fi

echo ""
