#!/bin/bash
# Bridge and Network Health Monitoring Script
# Version: 1.0
# Last Updated: 2026-01-24

set -euo pipefail

# Configuration
RPC_URL="http://192.168.11.211:8545"
BRIDGE="0xBd5F698E6490A6126E0F3DF6Ce4E83856092e239"
ROUTER="0xd49b579dfc5912fa7caa76893302c6e58f231431"
WETH9="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
LINK="0x362E9a45Ef6e554760f9671938235Cbc9b6E80Ed"

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

# Check if cast is available
if ! command -v cast &> /dev/null; then
    echo -e "${RED}❌ Error: 'cast' command not found${NC}"
    echo "Install Foundry: https://book.getfoundry.sh/getting-started/installation"
    exit 1
fi

echo "════════════════════════════════════════════════════════"
echo "   🔍 Bridge & Network Health Monitor"
echo "════════════════════════════════════════════════════════"
echo ""
echo "Timestamp: $(date '+%Y-%m-%d %H:%M:%S')"
echo ""

# Network Health Check
echo "📡 NETWORK STATUS"
echo "────────────────────────────────────────────────────────"

BLOCK=$(cast block-number --rpc-url $RPC_URL 2>/dev/null || echo "ERROR")
if [ "$BLOCK" != "ERROR" ]; then
    echo -e "${GREEN}✅ Block Number:${NC} $BLOCK"
    
    # Check block timestamp
    TIMESTAMP=$(cast block latest --rpc-url $RPC_URL 2>/dev/null | grep timestamp | awk '{print $2}')
    CURRENT_TIME=$(date +%s)
    BLOCK_AGE=$((CURRENT_TIME - TIMESTAMP))
    
    if [ $BLOCK_AGE -lt 10 ]; then
        echo -e "${GREEN}✅ Block Age:${NC} ${BLOCK_AGE}s (healthy)"
    elif [ $BLOCK_AGE -lt 30 ]; then
        echo -e "${YELLOW}⚠️  Block Age:${NC} ${BLOCK_AGE}s (slow)"
    else
        echo -e "${RED}❌ Block Age:${NC} ${BLOCK_AGE}s (STALE - network may be down)"
    fi
else
    echo -e "${RED}❌ Network:${NC} Cannot connect to RPC"
fi

# Check peer count
PEERS=$(cast rpc net_peerCount --rpc-url $RPC_URL 2>/dev/null || echo "0")
PEER_COUNT=$(echo "$PEERS" | sed 's/^0x//' | awk '{print sprintf("%d", "0x"$0)}')
if [ -z "$PEER_COUNT" ]; then PEER_COUNT=0; fi
if [ $PEER_COUNT -ge 10 ]; then
    echo -e "${GREEN}✅ Peer Count:${NC} $PEER_COUNT"
elif [ $PEER_COUNT -ge 5 ]; then
    echo -e "${YELLOW}⚠️  Peer Count:${NC} $PEER_COUNT (low)"
else
    echo -e "${RED}❌ Peer Count:${NC} $PEER_COUNT (CRITICAL)"
fi

echo ""

# Bridge Status
echo "🌉 BRIDGE STATUS"
echo "────────────────────────────────────────────────────────"

# Check bridge balance
BRIDGE_BAL=$(cast call $WETH9 "balanceOf(address)(uint256)" $BRIDGE --rpc-url $RPC_URL 2>/dev/null || echo "ERROR")
if [ "$BRIDGE_BAL" != "ERROR" ]; then
    BRIDGE_ETH=$(echo "scale=6; $BRIDGE_BAL / 1000000000000000000" | bc)
    echo -e "${GREEN}✅ Bridge WETH9 Balance:${NC} ${BRIDGE_ETH} WETH9"
else
    echo -e "${RED}❌ Bridge Balance:${NC} Cannot query"
fi

# Check router fee collection
ROUTER_BAL=$(cast call $LINK "balanceOf(address)(uint256)" $ROUTER --rpc-url $RPC_URL 2>/dev/null || echo "ERROR")
if [ "$ROUTER_BAL" != "ERROR" ]; then
    ROUTER_LINK=$(echo "scale=6; $ROUTER_BAL / 1000000000000000000" | bc)
    echo -e "${GREEN}✅ Router LINK Balance:${NC} ${ROUTER_LINK} LINK (fees collected)"
else
    echo -e "${RED}❌ Router Balance:${NC} Cannot query"
fi

# Check if bridge contract has code
BRIDGE_CODE=$(cast code $BRIDGE --rpc-url $RPC_URL 2>/dev/null || echo "0x")
if [ "$BRIDGE_CODE" != "0x" ] && [ ${#BRIDGE_CODE} -gt 10 ]; then
    echo -e "${GREEN}✅ Bridge Contract:${NC} Deployed"
else
    echo -e "${RED}❌ Bridge Contract:${NC} No code found"
fi

# Check if router contract has code
ROUTER_CODE=$(cast code $ROUTER --rpc-url $RPC_URL 2>/dev/null || echo "0x")
if [ "$ROUTER_CODE" != "0x" ] && [ ${#ROUTER_CODE} -gt 10 ]; then
    echo -e "${GREEN}✅ Router Contract:${NC} Deployed"
else
    echo -e "${RED}❌ Router Contract:${NC} No code found"
fi

# Check destination configuration
DEST_CHECK=$(cast call $BRIDGE "getDestination(uint64)(address,bool)" 5009297550715157269 --rpc-url $RPC_URL 2>/dev/null || echo "ERROR")
if [ "$DEST_CHECK" != "ERROR" ] && echo "$DEST_CHECK" | grep -q "true"; then
    echo -e "${GREEN}✅ Mainnet Destination:${NC} Enabled"
else
    echo -e "${RED}❌ Mainnet Destination:${NC} Not enabled or cannot query"
fi

echo ""

# System Summary
echo "📊 SYSTEM SUMMARY"
echo "────────────────────────────────────────────────────────"

# Count issues
ISSUES=0
if [ "$BLOCK" = "ERROR" ]; then ((ISSUES++)); fi
if [ $BLOCK_AGE -gt 30 ] 2>/dev/null; then ((ISSUES++)); fi
if [ $PEER_COUNT -lt 5 ] 2>/dev/null; then ((ISSUES++)); fi
if [ "$BRIDGE_BAL" = "ERROR" ]; then ((ISSUES++)); fi
if [ "$ROUTER_BAL" = "ERROR" ]; then ((ISSUES++)); fi

if [ $ISSUES -eq 0 ]; then
    echo -e "${GREEN}✅ OVERALL STATUS: HEALTHY${NC}"
    echo "All systems operational"
    EXIT_CODE=0
elif [ $ISSUES -le 2 ]; then
    echo -e "${YELLOW}⚠️  OVERALL STATUS: DEGRADED${NC}"
    echo "Some issues detected ($ISSUES warnings)"
    EXIT_CODE=1
else
    echo -e "${RED}❌ OVERALL STATUS: CRITICAL${NC}"
    echo "Multiple issues detected ($ISSUES errors)"
    EXIT_CODE=2
fi

echo ""
echo "════════════════════════════════════════════════════════"
echo ""

# Optionally log to file
if [ "${LOG_TO_FILE:-false}" = "true" ]; then
    LOG_FILE="${LOG_FILE:-/var/log/bridge-health.log}"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - Status: $EXIT_CODE, Issues: $ISSUES" >> "$LOG_FILE"
fi

exit $EXIT_CODE
