#!/usr/bin/env bash
# Verify explorer API access (Blockscout at /api/).
# Run from Proxmox host or inside VMID 5000.
# Usage: ./verify-explorer-api-access.sh [BASE_URL]
#   BASE_URL defaults to https://explorer.d-bis.org

set -euo pipefail

BASE_URL="${1:-https://explorer.d-bis.org}"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# Detect execution context: inside LXC (VMID 5000) or on host
RUN_LOCAL=false
if [ -f /var/www/html/index.html ] 2>/dev/null || [ -d /var/www/html ] 2>/dev/null; then
    RUN_LOCAL=true
fi
if [ -n "${VMID:-}" ] && [ "${VMID}" = "5000" ]; then
    RUN_LOCAL=true
fi

EXEC_PREFIX=""
if [ "$RUN_LOCAL" = false ] && command -v pct &>/dev/null; then
    # Prefer VMID 5000; allow override
    TARGET_VMID="${EXPLORER_VMID:-5000}"
    if pct status "$TARGET_VMID" &>/dev/null; then
        EXEC_PREFIX="pct exec $TARGET_VMID --"
    fi
fi

PASS=0
FAIL=0

check() {
    local name="$1"
    if eval "$2"; then
        echo "✅ $name"
        ((PASS++)) || true
        return 0
    else
        echo "❌ $name"
        ((FAIL++)) || true
        return 1
    fi
}

echo "=============================================="
echo "Explorer API access verification"
echo "BASE_URL=$BASE_URL"
echo "=============================================="
echo ""

# 1) Backend on port 4000 (only when we can run inside the VM)
if [ -n "$EXEC_PREFIX" ] || [ "$RUN_LOCAL" = true ]; then
    if $EXEC_PREFIX bash -c 'curl -sS -f -o /dev/null -w "%{http_code}" --connect-timeout 5 http://127.0.0.1:4000/api/v2/stats 2>/dev/null | grep -q 200'; then
        echo "✅ Blockscout (port 4000) responds with 200"
        ((PASS++)) || true
    else
        echo "❌ Blockscout (port 4000) not responding with 200 (service down or not Blockscout?)"
        ((FAIL++)) || true
    fi
else
    echo "⏭ Skipping local port 4000 check (not inside VM and pct not used)"
fi

# 2) Nginx config has /api/ -> 4000
if [ -n "$EXEC_PREFIX" ] || [ "$RUN_LOCAL" = true ]; then
    if $EXEC_PREFIX bash -c 'grep -r "location /api/" /etc/nginx 2>/dev/null | head -1' | grep -q .; then
        if $EXEC_PREFIX bash -c 'grep -A2 "location /api/" /etc/nginx/sites-enabled/* 2>/dev/null || grep -A2 "location /api/" /etc/nginx/sites-available/* 2>/dev/null' | grep -q 'proxy_pass.*4000'; then
            echo "✅ Nginx has location /api/ proxying to port 4000"
            ((PASS++)) || true
        else
            echo "❌ Nginx has location /api/ but not proxying to 4000"
            ((FAIL++)) || true
        fi
    else
        echo "❌ Nginx config has no location /api/"
        ((FAIL++)) || true
    fi
else
    echo "⏭ Skipping nginx config check (not inside VM and pct not used)"
fi

# 3) Public URL /api/v2/stats returns 200 (curl from this machine, no pct)
HTTP_CODE="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 10 "$BASE_URL/api/v2/stats" 2>/dev/null || echo 000)"
if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ $BASE_URL/api/v2/stats returns 200"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/api/v2/stats returned $HTTP_CODE (expected 200)"
    ((FAIL++)) || true
fi

# 4) Public URL /api/v2/blocks returns 200
HTTP_CODE="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 10 "$BASE_URL/api/v2/blocks?page=1&page_size=1" 2>/dev/null || echo 000)"
if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ $BASE_URL/api/v2/blocks returns 200"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/api/v2/blocks returned $HTTP_CODE (expected 200)"
    ((FAIL++)) || true
fi

# 5) Public URL /api/v2/transactions returns 200
HTTP_CODE="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 10 "$BASE_URL/api/v2/transactions?page=1&page_size=1" 2>/dev/null || echo 000)"
if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ $BASE_URL/api/v2/transactions returns 200"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/api/v2/transactions returned $HTTP_CODE (expected 200)"
    ((FAIL++)) || true
fi

# 6) Explorer root returns 200
HTTP_CODE="$(curl -sS -o /dev/null -w "%{http_code}" --connect-timeout 10 "$BASE_URL/" 2>/dev/null || echo 000)"
if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ $BASE_URL/ (explorer frontend) returns 200"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/ returned $HTTP_CODE (expected 200)"
    ((FAIL++)) || true
fi

# 7) Snap companion site /snap/ returns 200 or 301 (follow redirects for content)
SNAP_OUT="$(curl -sS -L -w '\n%{http_code}' --connect-timeout 10 "$BASE_URL/snap/" 2>/dev/null)" || true
SNAP_BODY="$(echo "$SNAP_OUT" | head -n -1)"
SNAP_CODE="$(echo "$SNAP_OUT" | tail -n 1)"
if [ "$SNAP_CODE" = "200" ] || [ "$SNAP_CODE" = "301" ]; then
    echo "✅ $BASE_URL/snap/ (Chain 138 Snap site) returns $SNAP_CODE"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/snap/ returned $SNAP_CODE (expected 200 or 301)"
    ((FAIL++)) || true
fi

# 8) /snap/ response contains Snap app content (skip if 301 — redirect may not include body)
if echo "$SNAP_BODY" | head -c 8192 | grep -qE 'Connect|template-snap|Snap|MetaMask'; then
    echo "✅ $BASE_URL/snap/ contains Snap app content"
    ((PASS++)) || true
elif [ "$SNAP_CODE" = "301" ]; then
    echo "⏭ $BASE_URL/snap/ returned 301 (redirect); content check skipped"
else
    echo "❌ $BASE_URL/snap/ response missing expected content (Connect|Snap|MetaMask)"
    ((FAIL++)) || true
fi

# 9) Nginx has location /snap/ (when we can run inside VM)
if [ -n "$EXEC_PREFIX" ] || [ "$RUN_LOCAL" = true ]; then
    if $EXEC_PREFIX bash -c 'grep -q "location /snap/" /etc/nginx/sites-available/blockscout 2>/dev/null'; then
        echo "✅ Nginx has location /snap/"
        ((PASS++)) || true
    else
        echo "❌ Nginx config has no location /snap/"
        ((FAIL++)) || true
    fi
else
    echo "⏭ Skipping nginx /snap/ check (not inside VM and pct not used)"
fi

echo ""
echo "=============================================="
echo "Result: $PASS passed, $FAIL failed"
echo "=============================================="
if [ "$FAIL" -gt 0 ]; then
    echo ""
    echo "See: $REPO_ROOT/docs/EXPLORER_API_ACCESS.md"
    exit 1
fi
exit 0
