#!/usr/bin/env bash
# Fix MetaMask ethers library loading issue in Blockscout frontend
# This script deploys the fixed frontend to the blockscout container

set -euo pipefail

VMID="${VMID:-5000}"
IP="${IP:-192.168.11.140}"
PASSWORD="${PASSWORD:-L@kers2010}"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
FRONTEND_FILE="$PROJECT_ROOT/explorer-monorepo/frontend/public/index.html"

if [ ! -f "$FRONTEND_FILE" ]; then
    log_error "Frontend file not found: $FRONTEND_FILE"
    exit 1
fi

echo "════════════════════════════════════════════════════════"
echo "Fix Blockscout MetaMask Ethers Error"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Check if container is accessible
log_step "Step 1: Checking container accessibility..."
if ! sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "echo 'Connection successful'" 2>/dev/null; then
    log_error "Cannot connect to container at $IP"
    log_info "Trying alternative: pct exec $VMID"
    if ! pct exec "$VMID" -- echo "Connection successful" 2>/dev/null; then
        log_error "Cannot access container VMID $VMID"
        exit 1
    fi
    USE_PCT=true
else
    USE_PCT=false
fi
log_success "Container is accessible"

# Step 2: Check if blockscout is running in Docker
log_step "Step 2: Checking Blockscout Docker container..."
if [ "$USE_PCT" = true ]; then
    BLOCKSCOUT_RUNNING=$(pct exec "$VMID" -- docker ps --filter "name=blockscout" --format "{{.Names}}" 2>/dev/null || echo "")
else
    BLOCKSCOUT_RUNNING=$(sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "docker ps --filter 'name=blockscout' --format '{{.Names}}'" 2>/dev/null || echo "")
fi

if [ -z "$BLOCKSCOUT_RUNNING" ]; then
    log_warn "Blockscout Docker container not found"
    log_info "The frontend might be served separately via nginx or another web server"
else
    log_success "Blockscout container found: $BLOCKSCOUT_RUNNING"
fi

# Step 3: Check for nginx or other web server serving frontend
log_step "Step 3: Checking for web server configuration..."
if [ "$USE_PCT" = true ]; then
    NGINX_CONFIG=$(pct exec "$VMID" -- find /etc/nginx -name "*.conf" -type f 2>/dev/null | head -1 || echo "")
    FRONTEND_DIR=$(pct exec "$VMID" -- find /opt /var/www -type d -name "frontend" -o -name "public" 2>/dev/null | head -1 || echo "")
else
    NGINX_CONFIG=$(sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "find /etc/nginx -name '*.conf' -type f 2>/dev/null | head -1" || echo "")
    FRONTEND_DIR=$(sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "find /opt /var/www -type d -name 'frontend' -o -name 'public' 2>/dev/null | head -1" || echo "")
fi

if [ -n "$NGINX_CONFIG" ]; then
    log_info "Nginx configuration found: $NGINX_CONFIG"
fi

if [ -n "$FRONTEND_DIR" ]; then
    log_success "Frontend directory found: $FRONTEND_DIR"
    DEPLOY_DIR="$FRONTEND_DIR"
else
    log_warn "No frontend directory found"
    log_info "Checking if frontend is served from blockscout static assets..."
    if [ "$USE_PCT" = true ]; then
        BLOCKSCOUT_STATIC=$(pct exec "$VMID" -- docker exec "$BLOCKSCOUT_RUNNING" find /app/apps/explorer/priv/static -name "index.html" 2>/dev/null | head -1 || echo "")
    else
        BLOCKSCOUT_STATIC=$(sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "docker exec $BLOCKSCOUT_RUNNING find /app/apps/explorer/priv/static -name 'index.html' 2>/dev/null | head -1" || echo "")
    fi
    
    if [ -n "$BLOCKSCOUT_STATIC" ]; then
        log_info "Blockscout static assets found"
        DEPLOY_DIR="docker:$BLOCKSCOUT_RUNNING:$BLOCKSCOUT_STATIC"
    else
        log_error "Cannot determine frontend deployment location"
        log_info "Please manually copy the fixed index.html to the appropriate location"
        exit 1
    fi
fi

# Step 4: Deploy fixed frontend
log_step "Step 4: Deploying fixed frontend..."

# Check nginx config to find frontend location
if [ "$USE_PCT" = false ]; then
    NGINX_ROOT=$(sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "grep -E '^\s*root\s+' /etc/nginx/sites-available/blockscout 2>/dev/null | awk '{print \$2}' | tr -d ';' | head -1" || echo "")
    
    if [ -n "$NGINX_ROOT" ]; then
        DEPLOY_DIR="$NGINX_ROOT"
        log_info "Found nginx root: $DEPLOY_DIR"
    else
        # Default location
        DEPLOY_DIR="/var/www/html"
        log_info "Using default location: $DEPLOY_DIR"
    fi
    
    # Create backup
    log_info "Creating backup..."
    sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "cp $DEPLOY_DIR/index.html $DEPLOY_DIR/index.html.backup.\$(date +%Y%m%d_%H%M%S) 2>/dev/null || true"
    
    # Deploy file
    log_info "Deploying to: $DEPLOY_DIR"
    sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no "$FRONTEND_FILE" "root@$IP:$DEPLOY_DIR/index.html"
    
    # Verify deployment
    if sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "grep -q 'unpkg.com' $DEPLOY_DIR/index.html 2>/dev/null"; then
        log_success "Frontend deployed successfully (fallback CDN detected)"
    else
        log_warn "Deployment completed but fallback CDN not detected - please verify manually"
    fi
else
    log_info "Using pct command for deployment..."
    # Try to find nginx root via pct
    NGINX_ROOT=$(pct exec "$VMID" -- grep -E '^\s*root\s+' /etc/nginx/sites-available/blockscout 2>/dev/null | awk '{print $2}' | tr -d ';' | head -1 || echo "")
    
    if [ -n "$NGINX_ROOT" ]; then
        DEPLOY_DIR="$NGINX_ROOT"
    else
        DEPLOY_DIR="/var/www/html"
    fi
    
    pct push "$VMID" "$FRONTEND_FILE" "$DEPLOY_DIR/index.html"
    log_success "Frontend deployed to: $DEPLOY_DIR"
fi

# Step 5: Restart services if needed
log_step "Step 5: Restarting services..."
if [ -n "$NGINX_CONFIG" ]; then
    if [ "$USE_PCT" = true ]; then
        pct exec "$VMID" -- systemctl reload nginx 2>/dev/null || true
    else
        sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "systemctl reload nginx" 2>/dev/null || true
    fi
    log_success "Nginx reloaded"
fi

# Summary
echo ""
echo "════════════════════════════════════════════════════════"
log_success "MetaMask Ethers Fix Deployed!"
echo "════════════════════════════════════════════════════════"
echo ""
echo "✅ Fixed Issues:"
echo "   - Added fallback CDN for ethers library (unpkg.com)"
echo "   - Added ethers availability checks in all functions"
echo "   - Improved error handling for library loading"
echo ""
echo "📝 Changes Made:"
echo "   - Primary CDN: https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js"
echo "   - Fallback CDN: https://unpkg.com/ethers@5.7.2/dist/ethers.umd.min.js"
echo "   - Added ensureEthers() helper function"
echo "   - Added checks before all ethers usage"
echo ""
echo "🔄 Next Steps:"
echo "   1. Clear browser cache and refresh the page"
echo "   2. Test MetaMask connection"
echo "   3. Verify ethers library loads correctly"
echo ""
log_success "Fix deployment complete!"

