#!/usr/bin/env bash
# Fund Bridge Contracts with LINK Tokens
# Automates the funding of both bridge contracts
# Usage: ./fund-bridge-contracts.sh [amount_per_bridge_link]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
source "$PROJECT_ROOT/scripts/lib/address-inventory.sh"

# 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}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

load_explorer_runtime_env

# Configuration
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
LINK_TOKEN="$(resolve_address_value LINK_TOKEN LINK_TOKEN 0x326C977E6efc84E512bB9C30f76E30c160eD06FB)"
WETH9_BRIDGE="$(resolve_address_value CCIPWETH9_BRIDGE CCIPWETH9_BRIDGE 0xcacfd227A040002e49e2e01626363071324f820a)"
WETH10_BRIDGE="$(resolve_address_value CCIPWETH10_BRIDGE CCIPWETH10_BRIDGE 0xe0E93247376aa097dB308B92e6Ba36bA015535D0)"

AMOUNT_PER_BRIDGE="${1:-10}"  # Default 10 LINK per bridge

if [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not available in effective environment"
    exit 1
fi

ACCOUNT=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$ACCOUNT" ]; then
    log_error "Could not derive address from PRIVATE_KEY"
    exit 1
fi

log_info "========================================="
log_info "Fund Bridge Contracts with LINK"
log_info "========================================="
log_info ""
log_info "Account: $ACCOUNT"
log_info "Amount per bridge: $AMOUNT_PER_BRIDGE LINK"
log_info "Total: $(echo "scale=1; $AMOUNT_PER_BRIDGE * 2" | bc) LINK"
log_info ""

# Check LINK token
LINK_CODE=$(cast code "$LINK_TOKEN" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
if [ -z "$LINK_CODE" ] || [ "$LINK_CODE" = "0x" ]; then
    log_error "LINK token contract not deployed or empty"
    log_info "Address: $LINK_TOKEN"
    log_info "Action: Deploy LINK token contract first"
    exit 1
fi

# Check account LINK balance
LINK_BAL=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
LINK_BAL_ETH=$(cast --from-wei "$LINK_BAL" ether 2>/dev/null || echo "0")
TOTAL_NEEDED=$(echo "scale=1; $AMOUNT_PER_BRIDGE * 2" | bc 2>/dev/null || echo "0")

log_info "Account LINK Balance: $LINK_BAL_ETH LINK"
log_info "Total Needed: $TOTAL_NEEDED LINK"
log_info ""

if (( $(echo "$LINK_BAL_ETH < $TOTAL_NEEDED" | bc -l 2>/dev/null || echo 1) )); then
    log_error "Insufficient LINK balance"
    log_info "Need: $TOTAL_NEEDED LINK"
    log_info "Have: $LINK_BAL_ETH LINK"
    exit 1
fi

# Get optimal gas
if [ -f "$SCRIPT_DIR/get-optimal-gas-from-api.sh" ]; then
    OPTIMAL_GAS=$("$SCRIPT_DIR/get-optimal-gas-from-api.sh" "proposed" 2>/dev/null || echo "")
    if [ -z "$OPTIMAL_GAS" ] || [ "$OPTIMAL_GAS" = "0" ]; then
        CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
        OPTIMAL_GAS=$(echo "scale=0; $CURRENT_GAS * 1.5 / 1" | bc 2>/dev/null || echo "$CURRENT_GAS")
    fi
else
    CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    OPTIMAL_GAS=$(echo "scale=0; $CURRENT_GAS * 1.5 / 1" | bc 2>/dev/null || echo "$CURRENT_GAS")
fi

# Convert amount to wei
AMOUNT_WEI=$(cast --to-wei "$AMOUNT_PER_BRIDGE" ether 2>/dev/null || echo "")
if [ -z "$AMOUNT_WEI" ]; then
    log_error "Failed to convert amount to wei"
    exit 1
fi

# Fund WETH9 Bridge
log_info "Funding WETH9 Bridge..."
CURRENT_NONCE=$(cast nonce "$ACCOUNT" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

TX_OUTPUT=$(cast send "$LINK_TOKEN" \
    "transfer(address,uint256)" \
    "$WETH9_BRIDGE" \
    "$AMOUNT_WEI" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --gas-price "$OPTIMAL_GAS" \
    --nonce "$CURRENT_NONCE" \
    2>&1 || echo "FAILED")

if echo "$TX_OUTPUT" | grep -qE "(blockHash|transactionHash)"; then
    TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "(blockHash|transactionHash)[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' | head -1)
    log_success "WETH9 Bridge funded: $TX_HASH"
    ((CURRENT_NONCE++)) || true
    sleep 5
else
    log_error "Failed to fund WETH9 Bridge"
    log_error "$TX_OUTPUT"
    exit 1
fi

# Fund WETH10 Bridge
log_info ""
log_info "Funding WETH10 Bridge..."
TX_OUTPUT=$(cast send "$LINK_TOKEN" \
    "transfer(address,uint256)" \
    "$WETH10_BRIDGE" \
    "$AMOUNT_WEI" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --gas-price "$OPTIMAL_GAS" \
    --nonce "$CURRENT_NONCE" \
    2>&1 || echo "FAILED")

if echo "$TX_OUTPUT" | grep -qE "(blockHash|transactionHash)"; then
    TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "(blockHash|transactionHash)[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' | head -1)
    log_success "WETH10 Bridge funded: $TX_HASH"
else
    log_error "Failed to fund WETH10 Bridge"
    log_error "$TX_OUTPUT"
    exit 1
fi

# Verify funding
log_info ""
log_info "Verifying funding..."
sleep 10

WETH9_LINK=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH9_LINK_ETH=$(cast --from-wei "$WETH9_LINK" ether 2>/dev/null || echo "0")

WETH10_LINK=$(cast call "$LINK_TOKEN" "balanceOf(address)" "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH10_LINK_ETH=$(cast --from-wei "$WETH10_LINK" ether 2>/dev/null || echo "0")

log_info ""
log_info "Final Balances:"
log_info "  WETH9 Bridge: $WETH9_LINK_ETH LINK"
log_info "  WETH10 Bridge: $WETH10_LINK_ETH LINK"

if (( $(echo "$WETH9_LINK_ETH >= $AMOUNT_PER_BRIDGE" | bc -l 2>/dev/null || echo 0) )) && \
   (( $(echo "$WETH10_LINK_ETH >= $AMOUNT_PER_BRIDGE" | bc -l 2>/dev/null || echo 0) )); then
    log_success "✓ Both bridges funded successfully!"
    exit 0
else
    log_warn "⚠ Funding may still be pending"
    log_info "Wait a few minutes and check again"
    exit 0
fi
