#!/usr/bin/env bash
# Create Blockscout Landing Page - Uses API to display data
# Since Blockscout web routes return 404, create a simple landing page

set -euo pipefail

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 "Create Blockscout Landing Page"
echo "════════════════════════════════════════════════════════"
echo ""

# Step 1: Create landing page HTML
log_step "Step 1: Creating Blockscout landing page..."

cat > /tmp/blockscout-landing.html <<'HTML_EOF'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blockscout Explorer - Chain 138</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 900px;
            width: 100%;
            padding: 40px;
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 2.5em;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 1.1em;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 30px 0;
        }
        .stat-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            transition: transform 0.2s;
        }
        .stat-card:hover {
            transform: translateY(-5px);
        }
        .stat-value {
            font-size: 2em;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
        .stat-label {
            color: #666;
            font-size: 0.9em;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .api-section {
            margin-top: 40px;
            padding-top: 30px;
            border-top: 2px solid #eee;
        }
        .api-section h2 {
            color: #333;
            margin-bottom: 20px;
        }
        .api-link {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            margin: 10px 10px 10px 0;
            transition: background 0.2s;
        }
        .api-link:hover {
            background: #5568d3;
        }
        .loading {
            text-align: center;
            color: #666;
            padding: 20px;
        }
        .error {
            background: #fee;
            color: #c33;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 Blockscout Explorer</h1>
        <p class="subtitle">Chain ID 138 - d-bis.org Network</p>
        
        <div id="stats" class="stats">
            <div class="stat-card">
                <div class="stat-value" id="total-blocks">-</div>
                <div class="stat-label">Total Blocks</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="total-transactions">-</div>
                <div class="stat-label">Transactions</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="total-addresses">-</div>
                <div class="stat-label">Addresses</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="latest-block">-</div>
                <div class="stat-label">Latest Block</div>
            </div>
        </div>
        
        <div class="api-section">
            <h2>API Endpoints</h2>
            <p>Use these API endpoints to interact with the explorer:</p>
            <a href="/api/v2/stats" class="api-link">Network Stats</a>
            <a href="/api?module=block&action=eth_block_number" class="api-link">Latest Block</a>
            <p style="margin-top: 20px; color: #666;">
                <strong>Note:</strong> The web interface routes are not currently available. 
                Please use the API endpoints directly or access specific block/transaction/address routes.
            </p>
        </div>
    </div>
    
    <script>
        // Fetch network stats
        fetch('/api/v2/stats')
            .then(response => response.json())
            .then(data => {
                document.getElementById('total-blocks').textContent = parseInt(data.total_blocks || 0).toLocaleString();
                document.getElementById('total-transactions').textContent = parseInt(data.total_transactions || 0).toLocaleString();
                document.getElementById('total-addresses').textContent = parseInt(data.total_addresses || 0).toLocaleString();
                
                // Get latest block number
                fetch('/api?module=block&action=eth_block_number')
                    .then(response => response.json())
                    .then(blockData => {
                        if (blockData.result) {
                            const blockNum = parseInt(blockData.result, 16);
                            document.getElementById('latest-block').textContent = blockNum.toLocaleString();
                        }
                    })
                    .catch(err => {
                        console.error('Error fetching block number:', err);
                        document.getElementById('latest-block').textContent = 'Error';
                    });
            })
            .catch(err => {
                console.error('Error fetching stats:', err);
                document.getElementById('stats').innerHTML = '<div class="error">Error loading statistics. Please check API connectivity.</div>';
            });
    </script>
</body>
</html>
HTML_EOF

# Step 2: Upload landing page
log_step "Step 2: Uploading landing page..."
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no /tmp/blockscout-landing.html root@"$IP":/var/www/html/index.html
log_success "Landing page uploaded"

# Step 3: Update Nginx to serve landing page for root
log_step "Step 3: Updating Nginx configuration..."

# Download current config
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no root@"$IP":/etc/nginx/sites-available/blockscout /tmp/blockscout-current.conf

# Create updated config with landing page
cat > /tmp/blockscout-with-landing.conf <<'NGINX_EOF'
# Blockscout Nginx Configuration with Landing Page

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name explorer.d-bis.org 192.168.11.140;

    ssl_certificate /etc/letsencrypt/live/explorer.d-bis.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/explorer.d-bis.org/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384';
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    access_log /var/log/nginx/blockscout-access.log;
    error_log /var/log/nginx/blockscout-error.log;

    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
    send_timeout 300s;

    client_max_body_size 100M;

    # Root path - serve landing page, fallback to Blockscout if 404
    location = / {
        # Try Blockscout first
        proxy_pass http://127.0.0.1:4000/;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        
        # Intercept 404 and serve landing page
        proxy_intercept_errors on;
        error_page 404 = @serve_landing;
    }

    # Serve landing page
    location @serve_landing {
        root /var/www/html;
        try_files /index.html =404;
        add_header Content-Type text/html;
    }

    # API endpoints - always proxy to Blockscout
    location /api/ {
        proxy_pass http://127.0.0.1:4000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 300s;
    }

    # All other paths - proxy to Blockscout
    location / {
        proxy_pass http://127.0.0.1:4000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Connection "";
        proxy_buffering off;
        proxy_request_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }

    # Health check endpoint
    location /health {
        access_log off;
        proxy_pass http://127.0.0.1:4000/api/v2/status;
        proxy_set_header Host $host;
        add_header Content-Type application/json;
    }
}

# HTTP redirect
server {
    listen 80;
    listen [::]:80;
    server_name explorer.d-bis.org 192.168.11.140;

    location /.well-known/acme-challenge/ {
        root /var/www/html;
        try_files $uri =404;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

# WebSocket upgrade mapping
map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}
NGINX_EOF

# Upload new config
sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no /tmp/blockscout-with-landing.conf root@"$IP":/etc/nginx/sites-available/blockscout

# Step 4: Test and reload
log_step "Step 4: Testing and reloading Nginx..."
exec_container "nginx -t" || {
    log_error "Nginx configuration test failed!"
    exit 1
}

log_success "Nginx configuration test passed"
exec_container "systemctl reload nginx"
log_success "Nginx reloaded"

# Step 5: Test root path
log_step "Step 5: Testing root path..."
sleep 2

ROOT_TEST=$(curl -k -s -o /dev/null -w '%{http_code}' https://explorer.d-bis.org/ 2>&1)
log_info "Root path response: HTTP $ROOT_TEST"

if [ "$ROOT_TEST" = "200" ]; then
    log_success "Root path is now serving the landing page! (HTTP 200)"
elif [ "$ROOT_TEST" = "404" ]; then
    log_warn "Root path still returns 404"
else
    log_info "Root path returns HTTP $ROOT_TEST"
fi

echo ""
log_success "Landing page setup completed!"
log_info "Access: https://explorer.d-bis.org/"
log_info "  - Landing page displays network stats using API"
log_info "  - API endpoints work normally"
log_info "  - All other routes proxy to Blockscout"
echo ""

