#!/usr/bin/env bash
# Fix 502 Bad Gateway by ensuring Blockscout is running and responding on port 4000.
# Run on Proxmox host with VMID 5000, or: EXPLORER_VM_HOST=root@192.168.11.12 bash scripts/fix-502-blockscout.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
[ -f "$REPO_ROOT/../.env" ] && source "$REPO_ROOT/../.env" 2>/dev/null || true
[ -f "$REPO_ROOT/.env" ] && source "$REPO_ROOT/.env" 2>/dev/null || true

VMID="${EXPLORER_VMID:-5000}"
EXPLORER_NODE="${EXPLORER_VM_HOST:-${PROXMOX_R630_02:-192.168.11.12}}"
if [[ "$EXPLORER_NODE" == *"@"* ]]; then SSH_TARGET="$EXPLORER_NODE"; else SSH_TARGET="root@$EXPLORER_NODE"; fi

# Remote mode: no pct, run on node via SSH
if ! command -v pct &>/dev/null || ! pct list 2>/dev/null | grep -q "^$VMID "; then
    if [ -n "${EXPLORER_VM_HOST:-}" ] || [ -n "${PROXMOX_R630_02:-}" ]; then
        echo "Running on Proxmox node via SSH: $SSH_TARGET"
        scp -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SCRIPT_DIR/fix-502-blockscout.sh" "$SSH_TARGET:/tmp/fix-502-blockscout.sh" 2>/dev/null || true
        ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSH_TARGET" "EXPLORER_VM_HOST= bash /tmp/fix-502-blockscout.sh"
        exit $?
    else
        echo "Run this on the Proxmox host that has VMID $VMID, or set EXPLORER_VM_HOST=root@<node-ip>"
        exit 1
    fi
fi

EXEC_PREFIX="pct exec $VMID --"

echo "=============================================="
echo "Fix 502: Start Blockscout (VMID $VMID)"
echo "=============================================="
echo ""

# 1) Start postgres if present
echo "=== 1. PostgreSQL ==="
$EXEC_PREFIX docker start blockscout-postgres 2>/dev/null || true
$EXEC_PREFIX docker ps -a --format '{{.Names}} {{.Status}}' | grep -E "postgres|blockscout" || true
sleep 2
echo ""

# 2) Get Blockscout container name and restart it (app may have died inside)
echo "=== 2. Blockscout container (restart to recover app) ==="
CONTAINER=$($EXEC_PREFIX docker ps -a --format '{{.Names}}' 2>/dev/null | grep -E "blockscout" | grep -v postgres | head -1 | tr -d '\n\r' || true)
if [ -z "$CONTAINER" ]; then
    echo "⚠️  No Blockscout container found. Trying to create it from /opt/blockscout..."
    $EXEC_PREFIX bash -c 'cd /opt/blockscout 2>/dev/null && docker compose up -d blockscout 2>/dev/null || docker compose up -d 2>/dev/null' 2>&1 || true
    sleep 5
    CONTAINER=$($EXEC_PREFIX docker ps -a --format '{{.Names}}' 2>/dev/null | grep -E "blockscout" | grep -v postgres | head -1 | tr -d '\n\r' || true)
fi
if [ -z "$CONTAINER" ]; then
    echo "❌ Still no Blockscout container. Listing all:"
    $EXEC_PREFIX docker ps -a --format '{{.Names}}' 2>/dev/null || true
    echo ""
    echo "Start it manually: pct exec $VMID -- bash -c 'cd /opt/blockscout && docker compose up -d'"
    exit 1
else
    echo "Restarting container: $CONTAINER"
    RESTART_OUT=$($EXEC_PREFIX docker restart "$CONTAINER" 2>&1) || true
    echo "$RESTART_OUT"
    if echo "$RESTART_OUT" | grep -q "no space left on device"; then
        echo ""
        echo "❌ Disk full on VMID $VMID. Free space first, then rerun this script."
        echo "   From your machine: EXPLORER_VM_HOST=root@192.168.11.12 bash scripts/free-disk-vmid5000.sh"
        echo "   Or on Proxmox host: pct exec $VMID -- docker system prune -f; pct exec $VMID -- docker volume prune -f"
        exit 1
    fi
    echo "✅ Restart sent (waiting 15s for app to bind 4000...)"
    sleep 15
fi
echo ""

# 3) Show container status and recent logs
echo "=== 3. Container status & logs ==="
$EXEC_PREFIX docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}' | grep -E "NAMES|blockscout|postgres" || true
CONTAINER=$($EXEC_PREFIX docker ps -a --format '{{.Names}}' 2>/dev/null | grep -E "blockscout" | grep -v postgres | head -1 | tr -d '\n\r' || true)
if [ -n "$CONTAINER" ]; then
    echo ""
    echo "Recent logs ($CONTAINER):"
    $EXEC_PREFIX docker logs "$CONTAINER" 2>&1 | tail -30
else
    echo "⚠️  Could not get container name for logs"
fi
echo ""

# 4) Wait for port 4000
echo "=== 4. Waiting for API (port 4000) ==="
WAIT_MAX="${BLOCKSCOUT_WAIT_MAX:-60}"
WAIT_DONE=0
while [ $WAIT_DONE -lt $WAIT_MAX ]; do
    if $EXEC_PREFIX curl -sS -f -o /dev/null -w "%{http_code}" --connect-timeout 3 http://127.0.0.1:4000/api/v2/stats 2>/dev/null | grep -q 200; then
        echo "✅ Blockscout API responding"
        break
    fi
    sleep 5
    WAIT_DONE=$((WAIT_DONE + 5))
    echo "   ... ${WAIT_DONE}s"
done
if [ $WAIT_DONE -ge $WAIT_MAX ]; then
    echo "❌ API did not respond in ${WAIT_MAX}s. Common causes:"
    echo "   - Container exited: check logs above; run: pct exec $VMID -- docker logs $CONTAINER"
    echo "   - Database not ready or migrations needed: pct exec $VMID -- bash scripts/blockscout-quick-fix.sh (inside VM)"
    echo "   - Missing startup command in docker-compose: add 'command: bin/blockscout start' under blockscout service"
    exit 1
fi
echo ""

# 5) Quick public check
echo "=== 5. Public API check ==="
BASE="${EXPLORER_BASE_URL:-https://explorer.d-bis.org}"
CODE=$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 10 "$BASE/api/v2/stats" 2>/dev/null || echo "000")
if [ "$CODE" = "200" ]; then
    echo "✅ $BASE/api/v2/stats → 200"
else
    echo "⚠️  $BASE/api/v2/stats → $CODE (nginx/tunnel may need a moment)"
fi
echo ""
echo "=============================================="
echo "Done. If still 502, see docs/EXPLORER_API_ACCESS.md"
echo "=============================================="
