#!/usr/bin/env bash
# Verify Bridge Setup Checklist
# Checks all items from the "Do this now" checklist
# Usage: ./verify-bridge-setup-checklist.sh

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

if [[ -f "$SCRIPT_DIR/lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$PROJECT_ROOT"
elif [ -f "$PROJECT_ROOT/.env" ]; then
    set -a && source "$PROJECT_ROOT/.env" && set +a
fi

# Configuration
RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"
RPC_URL="${RPC_URL%$'\r'}"
RPC_URL="${RPC_URL%$'\n'}"
BRIDGE_ADDRESS="${CCIPWETH9_BRIDGE_CHAIN138:-0x971cD9D156f193df8051E48043C476e53ECd4693}"
LINK_TOKEN="${LINK_TOKEN:-0xb7721dD53A8c629d9f1Ba31a5819AFe250002b03}"
CCIP_ROUTER="${CCIP_ROUTER:-0x42DAb7b888Dd382bD5Adcf9E038dBF1fD03b4817}"
ETH_SELECTOR="5009297550715157269"  # Ethereum Mainnet

echo "========================================="
echo "Bridge Setup Checklist Verification"
echo "========================================="
echo ""
log_info "RPC URL: $RPC_URL"
log_info "Bridge Address: $BRIDGE_ADDRESS"
log_info "LINK Token: $LINK_TOKEN"
log_info "CCIP Router: $CCIP_ROUTER"
log_info "ETH Selector: $ETH_SELECTOR"
echo ""

# Check RPC connectivity
log_info "Checking RPC connectivity..."
if cast block-number --rpc-url "$RPC_URL" > /dev/null 2>&1; then
    BLOCK_NUM=$(cast block-number --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    log_success "RPC connected (Block: $BLOCK_NUM)"
else
    log_error "RPC connection failed"
    exit 1
fi
echo ""

# 1. Verify LINK token is deployed
log_info "1. Verifying LINK token deployment..."
LINK_CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null | wc -c || echo "0")
if [ "$LINK_CODE" -gt 100 ]; then
    log_success "LINK token deployed at $LINK_TOKEN"
    
    # Try to get token name/symbol
    LINK_NAME=$(cast call "$LINK_TOKEN" "name()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    LINK_SYMBOL=$(cast call "$LINK_TOKEN" "symbol()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
    if [ -n "$LINK_NAME" ] && [ "$LINK_NAME" != "0x" ]; then
        log_info "   Name: $LINK_NAME"
        log_info "   Symbol: $LINK_SYMBOL"
    fi
else
    log_error "LINK token NOT deployed at $LINK_TOKEN"
    log_warn "   Code length: $LINK_CODE (expected > 100)"
fi
echo ""

# 2. Verify router recognizes LINK as fee token
log_info "2. Verifying CCIP Router fee token..."
FEE_TOKEN=$(cast call "$CCIP_ROUTER" "getFeeToken()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -z "$FEE_TOKEN" ] || [ "$FEE_TOKEN" = "0x" ]; then
    # Try alternative method
    FEE_TOKEN=$(cast call "$CCIP_ROUTER" "feeToken()" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
fi

if [ -n "$FEE_TOKEN" ] && [ "$FEE_TOKEN" != "0x" ]; then
    # Extract address (remove padding)
    FEE_TOKEN_CLEAN=$(echo "$FEE_TOKEN" | sed 's/0x000000000000000000000000/0x/' | cut -c 1-42 || echo "")
    LINK_LOWER=$(echo "$LINK_TOKEN" | tr '[:upper:]' '[:lower:]')
    FEE_TOKEN_LOWER=$(echo "$FEE_TOKEN_CLEAN" | tr '[:upper:]' '[:lower:]')
    
    if [ "$FEE_TOKEN_LOWER" = "$LINK_LOWER" ]; then
        log_success "Router recognizes LINK as fee token"
        log_info "   Fee Token: $FEE_TOKEN_CLEAN"
    else
        log_warn "Router fee token mismatch"
        log_info "   Expected: $LINK_TOKEN"
        log_info "   Got: $FEE_TOKEN_CLEAN"
    fi
else
    log_warn "Could not query router fee token"
    log_info "   Router may not expose getFeeToken() method"
fi
echo ""

# 3. Verify destinations[ETH_SELECTOR] is set
log_info "3. Verifying destinations[$ETH_SELECTOR] configuration..."
DEST=$(cast call "$BRIDGE_ADDRESS" "destinations(uint64)" "$ETH_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

if [ -n "$DEST" ] && [ "$DEST" != "0x" ]; then
    # Parse destination struct: (uint64 chainSelector, address receiverBridge, bool enabled)
    # Output format varies, try to extract enabled status
    if echo "$DEST" | grep -q "true\|1"; then
        log_success "Destination enabled for ETH selector"
        
        # Try to extract receiver bridge address
        RECEIVER_BRIDGE=$(echo "$DEST" | grep -oE "0x[0-9a-fA-F]{40}" | head -1 || echo "")
        if [ -n "$RECEIVER_BRIDGE" ]; then
            log_info "   Receiver Bridge: $RECEIVER_BRIDGE"
        fi
        
        log_info "   Full response: $DEST"
    elif echo "$DEST" | grep -q "false\|0"; then
        log_error "Destination exists but is DISABLED"
        log_info "   Response: $DEST"
    else
        log_warn "Destination configured but status unclear"
        log_info "   Response: $DEST"
    fi
else
    log_error "Destination NOT configured for ETH selector"
    log_info "   Need to call: addDestination($ETH_SELECTOR, <receiverBridge>)"
fi
echo ""

# 4. Verify bridge contract function signature
log_info "4. Verifying bridge contract function signature..."
BRIDGE_CODE=$(cast code "$BRIDGE_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null | wc -c || echo "0")
if [ "$BRIDGE_CODE" -gt 100 ]; then
    log_success "Bridge contract exists"
    
    # Try to call sendCrossChain (will fail but confirms function exists)
    # We'll just verify the contract exists and has code
    log_info "   Function: sendCrossChain(uint64,address,uint256)"
    log_info "   Returns: bytes32 messageId"
else
    log_error "Bridge contract NOT found"
fi
echo ""

# Summary
echo "========================================="
echo "Summary"
echo "========================================="
echo ""

# Count checks
CHECKS_PASSED=0
CHECKS_TOTAL=4

[ "$LINK_CODE" -gt 100 ] && CHECKS_PASSED=$((CHECKS_PASSED + 1))
[ -n "$FEE_TOKEN" ] && [ "$FEE_TOKEN" != "0x" ] && CHECKS_PASSED=$((CHECKS_PASSED + 1))
[ -n "$DEST" ] && [ "$DEST" != "0x" ] && echo "$DEST" | grep -q "true\|1" && CHECKS_PASSED=$((CHECKS_PASSED + 1))
[ "$BRIDGE_CODE" -gt 100 ] && CHECKS_PASSED=$((CHECKS_PASSED + 1))

if [ "$CHECKS_PASSED" -eq "$CHECKS_TOTAL" ]; then
    log_success "All checks passed! ($CHECKS_PASSED/$CHECKS_TOTAL)"
    echo ""
    log_info "Next steps:"
    log_info "  1. Implement thirdweb UI with 3 buttons"
    log_info "  2. Test Wrap, Approve, and Bridge functionality"
else
    log_warn "Some checks failed ($CHECKS_PASSED/$CHECKS_TOTAL)"
    echo ""
    log_info "Action required:"
    [ "$LINK_CODE" -le 100 ] && log_info "  - Deploy LINK token or verify address"
    ([ -z "$FEE_TOKEN" ] || [ "$FEE_TOKEN" = "0x" ]) && log_info "  - Verify router fee token configuration"
    ([ -z "$DEST" ] || [ "$DEST" = "0x" ] || ! echo "$DEST" | grep -q "true\|1") && log_info "  - Configure destination: addDestination($ETH_SELECTOR, <receiverBridge>)"
    [ "$BRIDGE_CODE" -le 100 ] && log_info "  - Verify bridge contract deployment"
fi

echo ""
