#!/bin/bash
# Script to check all libraries and modules are loading correctly

echo "=========================================="
echo "Library and Module Loading Check"
echo "=========================================="
echo ""

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check counter
PASSED=0
FAILED=0
WARNINGS=0

check_url() {
    local url=$1
    local name=$2
    local required=${3:-true}
    
    echo -n "Checking $name... "
    http_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$url" 2>&1)
    
    if [ "$http_code" = "200" ] || [ "$http_code" = "301" ] || [ "$http_code" = "302" ]; then
        echo -e "${GREEN}✓ OK${NC} (HTTP $http_code)"
        ((PASSED++))
        return 0
    elif [ "$http_code" = "000" ]; then
        echo -e "${RED}✗ FAILED${NC} (Connection timeout/refused)"
        ((FAILED++))
        return 1
    else
        if [ "$required" = "true" ]; then
            echo -e "${RED}✗ FAILED${NC} (HTTP $http_code)"
            ((FAILED++))
            return 1
        else
            echo -e "${YELLOW}⚠ WARNING${NC} (HTTP $http_code - may be expected)"
            ((WARNINGS++))
            return 2
        fi
    fi
}

echo "=== External CDN Libraries ==="
check_url "https://cdn.jsdelivr.net/npm/ethers@5.7.2/dist/ethers.umd.min.js" "Ethers.js (Primary CDN - jsdelivr)"
check_url "https://unpkg.com/ethers@5.7.2/dist/ethers.umd.min.js" "Ethers.js (Fallback CDN - unpkg)"
check_url "https://cdnjs.cloudflare.com/ajax/libs/ethers/5.7.2/ethers.umd.min.js" "Ethers.js (Fallback CDN - cdnjs)"
check_url "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" "Font Awesome CSS"

echo ""
echo "=== API Endpoints ==="
check_url "https://explorer.d-bis.org/api/v2/stats" "Blockscout API - Stats"
check_url "https://explorer.d-bis.org/api/v2/blocks?page=1&page_size=1" "Blockscout API - Blocks"
check_url "https://explorer.d-bis.org/api/v2/transactions?page=1&page_size=1" "Blockscout API - Transactions"
# RPC endpoint check - use JSON-RPC call to VMID 2500
echo -n "Checking RPC Endpoint (VMID 2500 - JSON-RPC)... "
RPC_URL_CHECK="http://192.168.11.250:8545"
rpc_response=$(curl -s -X POST "$RPC_URL_CHECK" \
    -H "Content-Type: application/json" \
    -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' \
    -w "\nHTTP_CODE:%{http_code}" \
    --max-time 10 2>&1)
http_code=$(echo "$rpc_response" | grep "HTTP_CODE" | cut -d: -f2)
rpc_body=$(echo "$rpc_response" | grep -v "HTTP_CODE")

if echo "$rpc_body" | grep -q '"result"'; then
    chain_id=$(echo "$rpc_body" | grep -o '"result":"[^"]*"' | cut -d'"' -f4)
    echo -e "${GREEN}✓ OK${NC} (Chain ID: $chain_id)"
    ((PASSED++))
elif echo "$rpc_body" | grep -q '"error"'; then
    error_msg=$(echo "$rpc_body" | grep -o '"message":"[^"]*"' | cut -d'"' -f4 || echo "Unknown error")
    echo -e "${YELLOW}⚠ WARNING${NC} (RPC error: $error_msg)"
    ((WARNINGS++))
elif [ "$http_code" = "000" ] || [ -z "$http_code" ]; then
    echo -e "${RED}✗ FAILED${NC} (Connection refused - RPC may not be accessible from this host)"
    ((FAILED++))
else
    echo -e "${YELLOW}⚠ WARNING${NC} (HTTP $http_code - RPC endpoint may not be accessible)"
    ((WARNINGS++))
fi

echo ""
echo "=== Local API Endpoints (if backend is running) ==="
check_url "http://localhost:8080/health" "Local API Health Check" false
check_url "http://localhost:8080/api/v2/stats" "Local API Stats" false

echo ""
echo "=== File Checks ==="
FRONTEND_FILE="/home/intlc/projects/proxmox/explorer-monorepo/frontend/public/index.html"
if [ -f "$FRONTEND_FILE" ]; then
    echo -n "Frontend file exists... "
    echo -e "${GREEN}✓ OK${NC}"
    ((PASSED++))
    
    # Check for required constants
    echo -n "Checking for API constants... "
    if grep -q "const API_BASE = '/api';" "$FRONTEND_FILE" && \
       grep -q "const RPC_URL = 'http://192.168.11.250:8545';" "$FRONTEND_FILE" && \
       grep -q "const RPC_WS_URL = 'ws://192.168.11.250:8546';" "$FRONTEND_FILE" && \
       grep -q "const CHAIN_ID = 138;" "$FRONTEND_FILE" && \
       grep -q "const BLOCKSCOUT_API = 'https://explorer.d-bis.org/api';" "$FRONTEND_FILE"; then
        echo -e "${GREEN}✓ OK${NC}"
        ((PASSED++))
    else
        echo -e "${RED}✗ FAILED${NC} (Missing or incorrect constants)"
        ((FAILED++))
    fi
    
    # Check for ethers loading mechanism
    echo -n "Checking ethers loading mechanism... "
    if grep -q "checkEthers" "$FRONTEND_FILE" && \
       grep -q "window.ethersReady" "$FRONTEND_FILE"; then
        echo -e "${GREEN}✓ OK${NC}"
        ((PASSED++))
    else
        echo -e "${RED}✗ FAILED${NC} (Missing ethers loading mechanism)"
        ((FAILED++))
    fi
    
    # Check for CSP meta tag
    echo -n "Checking CSP configuration... "
    if grep -q "Content-Security-Policy" "$FRONTEND_FILE"; then
        echo -e "${GREEN}✓ OK${NC}"
        ((PASSED++))
    else
        echo -e "${YELLOW}⚠ WARNING${NC} (CSP not configured)"
        ((WARNINGS++))
    fi
    
    # Check for form label associations
    echo -n "Checking form label associations... "
    input_count=$(grep -c "<input" "$FRONTEND_FILE" || echo "0")
    label_with_for=$(grep -c 'for="' "$FRONTEND_FILE" || echo "0")
    if [ "$label_with_for" -ge "$input_count" ]; then
        echo -e "${GREEN}✓ OK${NC} ($label_with_for labels for $input_count inputs)"
        ((PASSED++))
    else
        echo -e "${YELLOW}⚠ WARNING${NC} (Some inputs may lack label associations)"
        ((WARNINGS++))
    fi
else
    echo -e "${RED}✗ FAILED${NC} (Frontend file not found)"
    ((FAILED++))
fi

echo ""
echo "=========================================="
echo "Summary"
echo "=========================================="
echo -e "${GREEN}Passed: $PASSED${NC}"
echo -e "${RED}Failed: $FAILED${NC}"
echo -e "${YELLOW}Warnings: $WARNINGS${NC}"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✓ All critical checks passed!${NC}"
    exit 0
else
    echo -e "${RED}✗ Some checks failed. Please review above.${NC}"
    exit 1
fi

