#!/usr/bin/env bash
# Fix allowances for both WETH9 and WETH10 bridges
# Usage: ./fix-all-allowances.sh [amount_in_eth]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_PROJECT="/home/intlc/projects/smom-dbis-138"

# 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"; }

source "$SOURCE_PROJECT/.env"

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
WETH9_ADDRESS="0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
WETH10_ADDRESS="0xf4BB2e28688e89fCcE3c0580D37d36A7672E8A9f"
WETH9_BRIDGE="${CCIPWETH9_BRIDGE_CHAIN138:-0x89dd12025bfCD38A168455A44B400e913ED33BE2}"
WETH10_BRIDGE="${CCIPWETH10_BRIDGE_CHAIN138:-0xe0E93247376aa097dB308B92e6Ba36bA015535D0}"

AMOUNT="${1:-7.0}"  # Default 7 ETH (for 7 chains)
AMOUNT_WEI=$(cast --to-wei "$AMOUNT" ether 2>/dev/null)

DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null)

log_info "========================================="
log_info "Fix All Bridge Allowances"
log_info "========================================="
log_info ""
log_info "Amount: $AMOUNT ETH"
log_info "Deployer: $DEPLOYER"
log_info ""

# Check current allowances
log_info "Checking current allowances..."
WETH9_ALLOW=$(cast call "$WETH9_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH10_ALLOW=$(cast call "$WETH10_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

WETH9_ALLOW_ETH=$(echo "scale=6; $WETH9_ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")
WETH10_ALLOW_ETH=$(echo "scale=6; $WETH10_ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")

log_info "WETH9 Allowance: $WETH9_ALLOW_ETH ETH"
log_info "WETH10 Allowance: $WETH10_ALLOW_ETH ETH"
log_info ""

# Fix WETH9 allowance
if [ "$WETH9_ALLOW" = "0" ] || [ "$WETH9_ALLOW" = "0x0000000000000000000000000000000000000000000000000000000000000000" ] || (( $(echo "$WETH9_ALLOW_ETH < $AMOUNT" | bc -l 2>/dev/null || echo 1) )); then
    log_info "Fixing WETH9 bridge allowance..."
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    TX_OUTPUT=$(cast send "$WETH9_ADDRESS" \
        "approve(address,uint256)" \
        "$WETH9_BRIDGE" \
        "$AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 20000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -qE "transactionHash"; then
        HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ WETH9 approval sent: $HASH"
        sleep 15
    elif echo "$TX_OUTPUT" | grep -q "Known transaction"; then
        log_warn "⚠ WETH9 approval already pending"
    else
        log_error "✗ WETH9 approval failed: $(echo "$TX_OUTPUT" | grep -E "Error" | head -1 || echo "Unknown")"
    fi
else
    log_success "✓ WETH9 allowance sufficient: $WETH9_ALLOW_ETH ETH"
fi

# Fix WETH10 allowance
if [ "$WETH10_ALLOW" = "0" ] || [ "$WETH10_ALLOW" = "0x0000000000000000000000000000000000000000000000000000000000000000" ] || (( $(echo "$WETH10_ALLOW_ETH < $AMOUNT" | bc -l 2>/dev/null || echo 1) )); then
    log_info "Fixing WETH10 bridge allowance..."
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    TX_OUTPUT=$(cast send "$WETH10_ADDRESS" \
        "approve(address,uint256)" \
        "$WETH10_BRIDGE" \
        "$AMOUNT_WEI" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 20000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -qE "transactionHash"; then
        HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ WETH10 approval sent: $HASH"
        sleep 15
    elif echo "$TX_OUTPUT" | grep -q "Known transaction"; then
        log_warn "⚠ WETH10 approval already pending"
    else
        log_error "✗ WETH10 approval failed: $(echo "$TX_OUTPUT" | grep -E "Error" | head -1 || echo "Unknown")"
    fi
else
    log_success "✓ WETH10 allowance sufficient: $WETH10_ALLOW_ETH ETH"
fi

log_info ""
log_info "Waiting 30 seconds for confirmations..."
sleep 30

# Verify allowances
log_info "Verifying allowances..."
WETH9_ALLOW=$(cast call "$WETH9_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$WETH9_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
WETH10_ALLOW=$(cast call "$WETH10_ADDRESS" "allowance(address,address)" "$DEPLOYER" "$WETH10_BRIDGE" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")

WETH9_ALLOW_ETH=$(echo "scale=6; $WETH9_ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")
WETH10_ALLOW_ETH=$(echo "scale=6; $WETH10_ALLOW / 1000000000000000000" | bc 2>/dev/null || echo "0")

log_info ""
log_success "========================================="
log_success "Allowance Fix Complete!"
log_success "========================================="
log_info ""
log_info "Final Status:"
log_info "  WETH9 Allowance: $WETH9_ALLOW_ETH ETH"
log_info "  WETH10 Allowance: $WETH10_ALLOW_ETH ETH"
log_info ""

if (( $(echo "$WETH9_ALLOW_ETH >= $AMOUNT" | bc -l 2>/dev/null || echo 0) )) && (( $(echo "$WETH10_ALLOW_ETH >= $AMOUNT" | bc -l 2>/dev/null || echo 0) )); then
    log_success "✅ All allowances are sufficient!"
else
    log_warn "⚠ Some allowances may still be pending. Wait a few minutes and check again."
fi

