#!/usr/bin/env bash
# Comprehensive Link and Functionality Test for Blockscout Explorer
# Tests all navigation, API endpoints, contract addresses, and interactive elements

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_test() { echo -e "${CYAN}[TEST]${NC} $1"; }

echo "════════════════════════════════════════════════════════"
echo "Explorer Link and Functionality Test"
echo "════════════════════════════════════════════════════════"
echo ""

FAILED=0
PASSED=0

test_endpoint() {
    local name="$1"
    local url="$2"
    log_test "Testing: $name"
    
    if response=$(curl -k -sL "$url" 2>&1); then
        if echo "$response" | grep -qE "(error|Error|ERROR|404|500)" && ! echo "$response" | grep -qE '"status":"1"|"result":'; then
            log_error "Failed: $name"
            ((FAILED++))
            return 1
        else
            log_success "Passed: $name"
            ((PASSED++))
            return 0
        fi
    else
        log_error "Failed: $name (connection error)"
        ((FAILED++))
        return 1
    fi
}

test_api_endpoint() {
    local name="$1"
    local url="$2"
    log_test "Testing API: $name"
    
    if response=$(curl -k -sL "$url" 2>&1); then
        if echo "$response" | python3 -c "import sys, json; d=json.load(sys.stdin); sys.exit(0 if ('result' in d or 'status' in d or 'total_blocks' in d) else 1)" 2>/dev/null; then
            log_success "Passed: $name"
            ((PASSED++))
            return 0
        else
            log_error "Failed: $name (invalid JSON or missing expected fields)"
            ((FAILED++))
            return 1
        fi
    else
        log_error "Failed: $name (connection error)"
        ((FAILED++))
        return 1
    fi
}

echo "════════════════════════════════════════════════════════"
echo "1. BASIC CONNECTIVITY TESTS"
echo "════════════════════════════════════════════════════════"
echo ""

test_endpoint "Home Page" "https://explorer.d-bis.org/"
test_endpoint "HTTPS Redirect" "http://explorer.d-bis.org/"

echo ""
echo "════════════════════════════════════════════════════════"
echo "2. API ENDPOINT TESTS"
echo "════════════════════════════════════════════════════════"
echo ""

# Get latest block number first
LATEST_BLOCK_HEX=$(curl -k -sL 'https://explorer.d-bis.org/api?module=block&action=eth_block_number' 2>&1 | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('result', '0x0'))" 2>/dev/null || echo "0x0")

test_api_endpoint "Network Stats API" "https://explorer.d-bis.org/api/v2/stats"
test_api_endpoint "Block Number API" "https://explorer.d-bis.org/api?module=block&action=eth_block_number"

if [ "$LATEST_BLOCK_HEX" != "0x0" ] && [ -n "$LATEST_BLOCK_HEX" ]; then
    test_api_endpoint "Block Data API" "https://explorer.d-bis.org/api?module=block&action=eth_get_block_by_number&tag=$LATEST_BLOCK_HEX&boolean=false"
fi

echo ""
echo "════════════════════════════════════════════════════════"
echo "3. CONTRACT ADDRESS TESTS"
echo "════════════════════════════════════════════════════════"
echo ""

# Contract addresses
CONTRACTS=(
    "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2:WETH9"
    "0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f:WETH10"
    "0x8078A09637e47Fa5Ed34F626046Ea2094a5CDE5e:CCIP Router"
    "0x105F8A15b819948a89153505762444Ee9f324684:CCIP Sender"
    "0x89dd12025bfCD38A168455A44B400e913ED33BE2:WETH9 Bridge"
    "0xe0E93247376aa097dB308B92e6Ba36bA015535D0:WETH10 Bridge"
)

for contract_info in "${CONTRACTS[@]}"; do
    IFS=':' read -r addr name <<< "$contract_info"
    test_api_endpoint "$name Balance" "https://explorer.d-bis.org/api?module=account&action=eth_get_balance&address=$addr&tag=latest"
done

echo ""
echo "════════════════════════════════════════════════════════"
echo "4. EXTERNAL RESOURCE TESTS"
echo "════════════════════════════════════════════════════════"
echo ""

test_endpoint "Font Awesome CDN" "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
test_endpoint "Ethers.js CDN" "https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js"

echo ""
echo "════════════════════════════════════════════════════════"
echo "5. NAVIGATION FUNCTION TESTS"
echo "════════════════════════════════════════════════════════"
echo ""

# Check if JavaScript functions exist in HTML
log_test "Checking JavaScript functions..."

FUNCTIONS=(
    "showHome"
    "showBlocks"
    "showTransactions"
    "showBridgeMonitoring"
    "showWETHUtilities"
    "connectMetaMask"
    "wrapWETH9"
    "unwrapWETH9"
    "wrapWETH10"
    "unwrapWETH10"
    "refreshWETHBalances"
    "handleSearch"
)

sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no root@"$IP" "cat /var/www/html/index.html" > /tmp/explorer-html.txt

for func in "${FUNCTIONS[@]}"; do
    if grep -q "function $func\|$func()" /tmp/explorer-html.txt; then
        log_success "Function exists: $func"
        ((PASSED++))
    else
        log_error "Function missing: $func"
        ((FAILED++))
    fi
done

echo ""
echo "════════════════════════════════════════════════════════"
echo "6. HTML STRUCTURE TESTS"
echo "════════════════════════════════════════════════════════"
echo ""

log_test "Checking HTML structure..."

ELEMENTS=(
    "navbar"
    "nav-links"
    "searchInput"
    "homeView"
    "blocksView"
    "transactionsView"
    "bridgeView"
    "wethView"
    "metamaskStatus"
)

for element in "${ELEMENTS[@]}"; do
    if grep -q "id=\"$element\"\|class=\"$element\"" /tmp/explorer-html.txt; then
        log_success "Element exists: $element"
        ((PASSED++))
    else
        log_warn "Element may be missing: $element (checking alternative patterns...)"
        if grep -qi "$element" /tmp/explorer-html.txt; then
            log_success "Element found (alternative pattern): $element"
            ((PASSED++))
        else
            log_error "Element missing: $element"
            ((FAILED++))
        fi
    fi
done

echo ""
echo "════════════════════════════════════════════════════════"
echo "7. CONTRACT ADDRESS REFERENCES"
echo "════════════════════════════════════════════════════════"
echo ""

log_test "Checking contract address references..."

for contract_info in "${CONTRACTS[@]}"; do
    IFS=':' read -r addr name <<< "$contract_info"
    if grep -qi "$addr" /tmp/explorer-html.txt; then
        log_success "Address referenced: $name ($addr)"
        ((PASSED++))
    else
        log_warn "Address not found: $name ($addr)"
        ((FAILED++))
    fi
done

echo ""
echo "════════════════════════════════════════════════════════"
echo "8. SSL/TLS TESTS"
echo "════════════════════════════════════════════════════════"
echo ""

log_test "Testing SSL configuration..."

if curl -k -sI "https://explorer.d-bis.org/" 2>&1 | grep -qi "HTTP/2\|200\|strict-transport-security"; then
    log_success "SSL/TLS working correctly"
    ((PASSED++))
else
    log_error "SSL/TLS issue detected"
    ((FAILED++))
fi

# Test HSTS header
if curl -k -sI "https://explorer.d-bis.org/" 2>&1 | grep -qi "strict-transport-security"; then
    log_success "HSTS header present"
    ((PASSED++))
else
    log_warn "HSTS header not found (may be in Cloudflare)"
    ((PASSED++))
fi

echo ""
echo "════════════════════════════════════════════════════════"
echo "TEST SUMMARY"
echo "════════════════════════════════════════════════════════"
echo ""

TOTAL=$((PASSED + FAILED))
PERCENTAGE=$((PASSED * 100 / TOTAL))

echo "Tests Passed: $PASSED / $TOTAL"
echo "Tests Failed: $FAILED / $TOTAL"
echo "Success Rate: $PERCENTAGE%"
echo ""

if [ $FAILED -eq 0 ]; then
    log_success "All tests passed! ✅"
    exit 0
elif [ $PERCENTAGE -ge 90 ]; then
    log_warn "Most tests passed, minor issues detected ⚠️"
    exit 0
else
    log_error "Multiple test failures detected ❌"
    exit 1
fi

