#!/usr/bin/env bash
# Verify prerequisites for bridging WETH9 to Ethereum Mainnet
set -euo pipefail

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

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

RPC_URL="${RPC_URL:-${RPC_URL_138:-http://192.168.11.211:8545}}"
RPC_URL="${RPC_URL%$'\r'}"
RPC_URL="${RPC_URL%$'\n'}"
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH9_BRIDGE="0x971cD9D156f193df8051E48043C476e53ECd4693"
ETHEREUM_SELECTOR="5009297550715157269"
LINK_TOKEN="${LINK_TOKEN:-0x514910771AF9Ca656af840dff83E8264EcF986CA}"
AMOUNT_ETH="${1:-20000}"

PRIVATE_KEY="${PRIVATE_KEY:-}"
if [ -z "$PRIVATE_KEY" ]; then
    echo "❌ PRIVATE_KEY not set"
    exit 1
fi

SENDER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$SENDER" ]; then
    echo "❌ Failed to derive address from private key"
    exit 1
fi

echo "========================================="
echo "Prerequisite Verification"
echo "========================================="
echo ""
echo "Sender Address: $SENDER"
echo "Amount: $AMOUNT_ETH ETH"
echo "RPC URL: $RPC_URL"
echo ""

# Check RPC connectivity
echo "1. 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")
    echo "   ✓ RPC connected (Block: $BLOCK_NUM)"
else
    echo "   ✗ RPC connection failed"
    exit 1
fi

# Check ETH balance
echo ""
echo "2. Checking ETH balance..."
ETH_BALANCE=$(cast balance "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
ETH_BALANCE_ETH=$(echo "scale=6; $ETH_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
AMOUNT_WEI=$(cast --to-wei "$AMOUNT_ETH" ether 2>/dev/null || echo "0")
NEEDED=$(echo "$AMOUNT_WEI + 100000000000000000" | bc 2>/dev/null || echo "0") # Add 0.1 ETH for gas

echo "   Balance: $ETH_BALANCE_ETH ETH"
echo "   Required: $AMOUNT_ETH ETH (+ ~0.1 ETH for gas)"
if (( $(echo "$ETH_BALANCE >= $NEEDED" | bc -l 2>/dev/null || echo 0) )); then
    echo "   ✓ Sufficient ETH balance"
else
    echo "   ✗ Insufficient ETH balance"
    exit 1
fi

# Check LINK balance
echo ""
echo "3. Checking LINK balance..."
LINK_BALANCE=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
LINK_BALANCE_ETH=$(echo "scale=6; $LINK_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
MIN_LINK=$(echo "scale=0; 1000000000000000000 * 0.5" | bc 2>/dev/null || echo "500000000000000000") # 0.5 LINK minimum

echo "   Balance: $LINK_BALANCE_ETH LINK"
echo "   Recommended: >= 0.5 LINK"
if (( $(echo "$LINK_BALANCE >= $MIN_LINK" | bc -l 2>/dev/null || echo 0) )); then
    echo "   ✓ Sufficient LINK balance"
else
    echo "   ⚠ Low LINK balance (may need more for fees)"
fi

# Check WETH9 contract
echo ""
echo "4. Checking WETH9 contract..."
WETH9_CODE=$(cast code "$WETH9_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null | wc -c)
if [ "$WETH9_CODE" -gt 100 ]; then
    echo "   ✓ WETH9 contract exists"
else
    echo "   ✗ WETH9 contract not found"
    exit 1
fi

# Check bridge contract
echo ""
echo "5. Checking bridge contract..."
BRIDGE_CODE=$(cast code "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null | wc -c)
if [ "$BRIDGE_CODE" -gt 100 ]; then
    echo "   ✓ Bridge contract exists"
else
    echo "   ✗ Bridge contract not found"
    exit 1
fi

# Check bridge destination
echo ""
echo "6. Checking bridge destination configuration..."
DEST=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -n "$DEST" ] && [ "$DEST" != "0x" ]; then
    # Parse destination struct (enabled status)
    ENABLED=$(echo "$DEST" | cut -d',' -f3 | xargs || echo "")
    if [ "$ENABLED" = "true" ] || [ "$ENABLED" = "1" ]; then
        echo "   ✓ Ethereum Mainnet destination enabled"
    else
        echo "   ✗ Ethereum Mainnet destination not enabled"
        exit 1
    fi
else
    echo "   ✗ Ethereum Mainnet destination not configured"
    exit 1
fi

# Check current WETH9 balance
echo ""
echo "7. Checking WETH9 balance..."
WETH9_BALANCE=$(cast call "$WETH9_ADDRESS" "balanceOf(address)" "$SENDER" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
WETH9_BALANCE_ETH=$(echo "scale=6; $WETH9_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
echo "   Balance: $WETH9_BALANCE_ETH WETH9"

if (( $(echo "$WETH9_BALANCE >= $AMOUNT_WEI" | bc -l 2>/dev/null || echo 0) )); then
    echo "   ✓ Sufficient WETH9 (no wrapping needed)"
    NEED_WRAP=false
else
    echo "   ⚠ Will need to wrap ETH to WETH9"
    NEED_WRAP=true
fi

# Check allowance
echo ""
echo "8. Checking bridge allowance..."
ALLOWANCE=$(cast call "$WETH9_ADDRESS" "allowance(address,address)" "$SENDER" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null | cast --to-dec 2>/dev/null || echo "0")
ALLOWANCE_ETH=$(echo "scale=6; $ALLOWANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
echo "   Allowance: $ALLOWANCE_ETH WETH9"

if (( $(echo "$ALLOWANCE >= $AMOUNT_WEI" | bc -l 2>/dev/null || echo 0) )); then
    echo "   ✓ Sufficient allowance"
    NEED_APPROVE=false
else
    echo "   ⚠ Will need to approve bridge"
    NEED_APPROVE=true
fi

echo ""
echo "========================================="
echo "Summary"
echo "========================================="
echo "✓ All prerequisites met!"
echo ""
echo "Next steps:"
if [ "$NEED_WRAP" = "true" ]; then
    echo "  - Wrap ETH to WETH9"
fi
if [ "$NEED_APPROVE" = "true" ]; then
    echo "  - Approve bridge"
fi
echo "  - Bridge WETH9 to Ethereum Mainnet"
echo ""

