#!/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)"
MISSION_CONTROL_SAMPLE_TX="${MISSION_CONTROL_SAMPLE_TX:-0x2f31d4f9a97be754b800f4af1a9eedf3b107d353bfa1a19e81417497a76c05c2}"
MISSION_CONTROL_SAMPLE_TOKEN="${MISSION_CONTROL_SAMPLE_TOKEN:-0x93E66202A11B1772E55407B32B44e5Cd8eda7f22}"

# 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" | grep -qE 'Connect|template-snap|Chain 138 Snap|Install MetaMask Flask|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|Chain 138 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

# 10) Visual Command Center returns 200
HTTP_CODE="$(curl -sS -o /tmp/chain138-command-center.verify.$$ -w "%{http_code}" --connect-timeout 10 "$BASE_URL/chain138-command-center.html" 2>/dev/null || echo 000)"
if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ $BASE_URL/chain138-command-center.html returns 200"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/chain138-command-center.html returned $HTTP_CODE (expected 200)"
    ((FAIL++)) || true
fi

# 11) Visual Command Center contains expected explorer architecture content
if grep -qE 'Visual Command Center|Mission Control|mainnet cW mint corridor' /tmp/chain138-command-center.verify.$$ 2>/dev/null; then
    echo "✅ $BASE_URL/chain138-command-center.html contains command-center content"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/chain138-command-center.html missing expected command-center content"
    ((FAIL++)) || true
fi
rm -f /tmp/chain138-command-center.verify.$$

# 12) Mission Control SSE stream returns 200 with text/event-stream
MC_STREAM_HEADERS="/tmp/mission-control-stream.headers.$$"
MC_STREAM_BODY="/tmp/mission-control-stream.body.$$"
MC_STREAM_EXIT=0
if ! curl -sS -N -D "$MC_STREAM_HEADERS" -o "$MC_STREAM_BODY" --connect-timeout 10 --max-time 8 \
    "$BASE_URL/explorer-api/v1/mission-control/stream" >/dev/null 2>&1; then
    MC_STREAM_EXIT=$?
fi
if grep -qE '^HTTP/[0-9.]+ 200' "$MC_STREAM_HEADERS" 2>/dev/null \
    && grep -qi '^content-type: text/event-stream' "$MC_STREAM_HEADERS" 2>/dev/null \
    && { [ "$MC_STREAM_EXIT" -eq 0 ] || [ "$MC_STREAM_EXIT" -eq 28 ]; } \
    && grep -qE '^(event|data):' "$MC_STREAM_BODY" 2>/dev/null; then
    echo "✅ $BASE_URL/explorer-api/v1/mission-control/stream returns Mission Control SSE"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/explorer-api/v1/mission-control/stream missing expected SSE response"
    ((FAIL++)) || true
fi
rm -f "$MC_STREAM_HEADERS" "$MC_STREAM_BODY"

# 13) Mission Control bridge trace returns labeled JSON
MC_TRACE_BODY="/tmp/mission-control-trace.body.$$"
HTTP_CODE="$(curl -sS -o "$MC_TRACE_BODY" -w "%{http_code}" --connect-timeout 10 \
    "$BASE_URL/explorer-api/v1/mission-control/bridge/trace?tx=$MISSION_CONTROL_SAMPLE_TX" 2>/dev/null || echo 000)"
if [ "$HTTP_CODE" = "200" ] \
    && grep -q '"tx_hash"' "$MC_TRACE_BODY" 2>/dev/null \
    && grep -q '"from_registry"' "$MC_TRACE_BODY" 2>/dev/null \
    && grep -q '"to_registry"' "$MC_TRACE_BODY" 2>/dev/null; then
    echo "✅ $BASE_URL/explorer-api/v1/mission-control/bridge/trace returns labeled trace JSON"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/explorer-api/v1/mission-control/bridge/trace failed verification"
    ((FAIL++)) || true
fi
rm -f "$MC_TRACE_BODY"

# 14) Mission Control liquidity proxy returns pool JSON
MC_LIQUIDITY_BODY="/tmp/mission-control-liquidity.body.$$"
HTTP_CODE="$(curl -sS -o "$MC_LIQUIDITY_BODY" -w "%{http_code}" --connect-timeout 10 \
    "$BASE_URL/explorer-api/v1/mission-control/liquidity/token/$MISSION_CONTROL_SAMPLE_TOKEN/pools" 2>/dev/null || echo 000)"
if [ "$HTTP_CODE" = "200" ] \
    && grep -q '"pools"' "$MC_LIQUIDITY_BODY" 2>/dev/null \
    && grep -q '"dex"' "$MC_LIQUIDITY_BODY" 2>/dev/null; then
    echo "✅ $BASE_URL/explorer-api/v1/mission-control/liquidity/token/.../pools returns pool JSON"
    ((PASS++)) || true
else
    echo "❌ $BASE_URL/explorer-api/v1/mission-control/liquidity/token/.../pools failed verification"
    ((FAIL++)) || true
fi
rm -f "$MC_LIQUIDITY_BODY"

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
