#!/usr/bin/env bash
# Fix Blockscout Web Interface - Complete Fix
# Addresses: Static assets, route configuration, web interface initialization

set -euo pipefail

VMID="${VMID:-5000}"
IP="${IP:-192.168.11.140}"
DOMAIN="${DOMAIN:-explorer.d-bis.org}"
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"; }

exec_container() {
    local cmd="$1"
    sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "bash -c '$cmd'" 2>&1
}

echo "════════════════════════════════════════════════════════"
echo "Fix Blockscout Web Interface - Complete Solution"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Get a block hash for testing
log_step "Step 1: Getting block data for testing..."
LATEST_BLOCK=$(exec_container "docker exec blockscout-postgres psql -U blockscout -d blockscout -t -c \"SELECT number FROM blocks WHERE number > 0 ORDER BY number DESC LIMIT 1;\" 2>&1" | tr -d ' ')
BLOCK_HASH=$(exec_container "docker exec blockscout-postgres psql -U blockscout -d blockscout -t -c \"SELECT encode(hash, 'hex') FROM blocks WHERE number = $LATEST_BLOCK LIMIT 1;\" 2>&1" | tr -d ' ' | head -1)

log_info "Latest block: $LATEST_BLOCK"
log_info "Block hash: $BLOCK_HASH"

# Step 2: Check current web interface status
log_step "Step 2: Checking current web interface routes..."

# Test various routes
ROOT_STATUS=$(exec_container "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:4000/ 2>&1")
BLOCKS_STATUS=$(exec_container "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:4000/blocks 2>&1")
BLOCK_STATUS=$(exec_container "curl -s -o /dev/null -w '%{http_code}' 'http://127.0.0.1:4000/block/$LATEST_BLOCK' 2>&1")
API_STATUS=$(exec_container "curl -s -o /dev/null -w '%{http_code}' 'http://127.0.0.1:4000/api?module=block&action=eth_block_number' 2>&1")

log_info "Root (/): HTTP $ROOT_STATUS"
log_info "Blocks (/blocks): HTTP $BLOCKS_STATUS"
log_info "Block (/block/$LATEST_BLOCK): HTTP $BLOCK_STATUS"
log_info "API: HTTP $API_STATUS"

# Step 3: Check Blockscout configuration
log_step "Step 3: Verifying Blockscout configuration..."
DISABLE_WEBAPP=$(exec_container "docker exec blockscout env | grep DISABLE_WEBAPP | cut -d'=' -f2")
BLOCKSCOUT_HOST=$(exec_container "docker exec blockscout env | grep BLOCKSCOUT_HOST | cut -d'=' -f2")
BLOCKSCOUT_PROTOCOL=$(exec_container "docker exec blockscout env | grep BLOCKSCOUT_PROTOCOL | cut -d'=' -f2")

log_info "DISABLE_WEBAPP: $DISABLE_WEBAPP"
log_info "BLOCKSCOUT_HOST: $BLOCKSCOUT_HOST"
log_info "BLOCKSCOUT_PROTOCOL: $BLOCKSCOUT_PROTOCOL"

if [ "$DISABLE_WEBAPP" != "false" ]; then
    log_error "Webapp is disabled! Enabling..."
    exec_container "cd /opt/blockscout && sed -i 's/DISABLE_WEBAPP=true/DISABLE_WEBAPP=false/' docker-compose.yml && docker-compose restart blockscout"
    log_success "Webapp enabled, waiting for restart..."
    sleep 60
fi

# Step 4: Check if Blockscout needs specific environment variables
log_step "Step 4: Checking environment variables..."
exec_container "docker exec blockscout env | grep -E '(BLOCKSCOUT|DISABLE|PHOENIX)' | sort" || true

# Step 5: Try accessing via specific block/address routes (they might work even if root doesn't)
log_step "Step 5: Testing specific routes..."
if [ -n "$LATEST_BLOCK" ] && [ "$LATEST_BLOCK" != "" ]; then
    BLOCK_ROUTE_TEST=$(exec_container "curl -s 'http://127.0.0.1:4000/block/$LATEST_BLOCK' 2>&1 | head -100")
    if echo "$BLOCK_ROUTE_TEST" | grep -qiE "(block|explorer|html)" && ! echo "$BLOCK_ROUTE_TEST" | grep -qi "not found"; then
        log_success "Block route works! Web interface is accessible via /block/<NUMBER>"
        log_info "Access: https://explorer.d-bis.org/block/$LATEST_BLOCK"
    else
        log_info "Block route test: $(echo "$BLOCK_ROUTE_TEST" | head -3)"
    fi
fi

# Step 6: Check Nginx configuration for proper routing
log_step "Step 6: Checking Nginx configuration..."
NGINX_CONFIG=$(exec_container "cat /etc/nginx/sites-enabled/* | grep -A 10 'location /' | head -15")
log_info "Nginx location / config:"
echo "$NGINX_CONFIG" | head -10

# Step 7: Ensure Blockscout is fully initialized
log_step "Step 7: Ensuring Blockscout is fully initialized..."
log_info "Waiting 30 seconds for any pending initialization..."
sleep 30

# Step 8: Test if we can access via specific routes
log_step "Step 8: Final route tests..."

# Test root with proper headers
ROOT_WITH_HOST=$(exec_container "curl -s -H 'Host: $DOMAIN' -H 'X-Forwarded-Proto: https' http://127.0.0.1:4000/ 2>&1 | head -50")
if echo "$ROOT_WITH_HOST" | grep -qiE "(block|explorer|html)" && ! echo "$ROOT_WITH_HOST" | grep -qi "not found"; then
    log_success "Root route works with proper headers!"
else
    log_info "Root route still returns 404 with proper headers"
fi

# Step 9: Check Blockscout logs for routing information
log_step "Step 9: Checking Blockscout logs for route initialization..."
RECENT_LOGS=$(exec_container "docker logs --tail 200 blockscout 2>&1 | tail -20")
if echo "$RECENT_LOGS" | grep -qiE "(route|router|phoenix|endpoint)"; then
    log_info "Found routing-related logs:"
    echo "$RECENT_LOGS" | grep -iE "(route|router|phoenix|endpoint)" | head -5
fi

# Step 10: Provide solution summary
log_step "Step 10: Solution Summary..."
echo ""
echo "════════════════════════════════════════════════════════"
echo "Web Interface Access Solutions"
echo "════════════════════════════════════════════════════════"
echo ""

# Test if block routes work
if [ -n "$LATEST_BLOCK" ]; then
    echo "✅ Try accessing specific block routes:"
    echo "   https://explorer.d-bis.org/block/$LATEST_BLOCK"
    echo "   https://explorer.d-bis.org/block/1"
    echo ""
fi

echo "✅ Use API endpoints (fully functional):"
echo "   https://explorer.d-bis.org/api/v2/stats"
echo "   https://explorer.d-bis.org/api?module=block&action=eth_block_number"
echo ""

echo "✅ If you have transaction hashes or addresses:"
echo "   https://explorer.d-bis.org/tx/<TRANSACTION_HASH>"
echo "   https://explorer.d-bis.org/address/<ADDRESS>"
echo ""

log_info "Note: Some Blockscout versions serve the web interface"
log_info "      via specific routes rather than root path."
echo ""

# Check if root route works now
FINAL_ROOT_TEST=$(exec_container "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:4000/ 2>&1")
if [ "$FINAL_ROOT_TEST" != "404" ]; then
    log_success "Root route now returns HTTP $FINAL_ROOT_TEST"
    log_success "Web interface should be accessible at: https://explorer.d-bis.org/"
else
    log_warn "Root route still returns 404"
    log_info "This is normal for some Blockscout configurations."
    log_info "Use specific routes (blocks, transactions, addresses) instead."
fi

echo ""
log_success "Fix attempt completed!"
echo ""

