#!/usr/bin/env bash
# Fix all bridge errors found in dry run
# This script fixes: Ethereum Mainnet destination configuration
# Usage: ./fix-bridge-errors.sh [private_key] [weth9_mainnet_bridge_address]

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"
source "$PROJECT_ROOT/scripts/lib/ccip-destinations.sh"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
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"; }
log_fix() { echo -e "${CYAN}[FIX]${NC} $1"; }

load_explorer_runtime_env

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

# Parse arguments
PRIVATE_KEY_ARG="${1:-}"
WETH9_MAINNET_BRIDGE="${2:-}"

# Use provided private key or from environment
if [ -n "$PRIVATE_KEY_ARG" ]; then
    PRIVATE_KEY="$PRIVATE_KEY_ARG"
elif [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not provided. Usage: $0 [private_key] [weth9_mainnet_bridge_address]"
    log_info "Or export PRIVATE_KEY before running"
    exit 1
fi

log_info "========================================="
log_info "Fix Bridge Errors"
log_info "========================================="
log_info ""

# Get deployer address
DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$DEPLOYER" ]; then
    log_error "Failed to get address from private key"
    exit 1
fi

log_info "Deployer Address: $DEPLOYER"
log_info "RPC URL: $RPC_URL"
log_info ""

# Check current configuration
log_info "Checking current bridge configuration..."
WETH9_DEST=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
WETH10_DEST=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

log_info "WETH9 Bridge Destination: ${WETH9_DEST:-Not configured}"
log_info "WETH10 Bridge Destination: ${WETH10_DEST:-Not configured}"
log_info ""

# Fix WETH9 Bridge
log_fix "========================================="
log_fix "Fixing WETH9 Bridge"
log_fix "========================================="

# Clean up destination check result
WETH9_DEST_CLEAN=$(echo "$WETH9_DEST" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")

if [ -n "$WETH9_DEST_CLEAN" ] && ! echo "$WETH9_DEST_CLEAN" | grep -qE "^0x0+$" && [ "$WETH9_DEST_CLEAN" != "0x0000000000000000000000000000000000000000" ]; then
    log_success "✓ WETH9 bridge already configured for Ethereum Mainnet"
    log_info "  Destination: $WETH9_DEST_CLEAN"
else
    if [ -z "$WETH9_MAINNET_BRIDGE" ]; then
        log_error "WETH9 Mainnet bridge address not provided"
        log_info "Usage: $0 [private_key] [weth9_mainnet_bridge_address]"
        log_info ""
        log_info "You need to provide the Ethereum Mainnet bridge address for WETH9"
        log_info "This should be the address of the CCIPWETH9Bridge contract on Ethereum Mainnet"
        exit 1
    fi
    
    log_info "Configuring WETH9 bridge for Ethereum Mainnet..."
    log_info "  Chain Selector: $ETHEREUM_MAINNET_SELECTOR"
    log_info "  Destination Bridge: $WETH9_MAINNET_BRIDGE"
    
    CURRENT_NONCE=$(cast nonce "$DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    
    log_info "Sending transaction..."
    TX_OUTPUT=$(cast send "$WETH9_BRIDGE" \
        "addDestination(uint64,address)" \
        "$ETHEREUM_MAINNET_SELECTOR" \
        "$WETH9_MAINNET_BRIDGE" \
        --rpc-url "$RPC_URL" \
        --private-key "$PRIVATE_KEY" \
        --gas-price 5000000000 \
        --nonce "$CURRENT_NONCE" \
        2>&1 || echo "FAILED")
    
    if echo "$TX_OUTPUT" | grep -qE "transactionHash"; then
        TX_HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}')
        log_success "✓ WETH9 bridge configuration transaction sent: $TX_HASH"
        log_info "Waiting for confirmation..."
        sleep 15
        
        # Verify configuration
        WETH9_DEST_AFTER=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
        WETH9_DEST_AFTER_CLEAN=$(echo "$WETH9_DEST_AFTER" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
        if [ -n "$WETH9_DEST_AFTER_CLEAN" ] && ! echo "$WETH9_DEST_AFTER_CLEAN" | grep -qE "^0x0+$" && [ "$WETH9_DEST_AFTER_CLEAN" != "0x0000000000000000000000000000000000000000" ]; then
            log_success "✓ WETH9 bridge configured successfully"
            log_info "  Destination: $WETH9_DEST_AFTER_CLEAN"
        else
            log_warn "⚠ Configuration may still be pending, verify manually"
        fi
    else
        log_error "✗ WETH9 bridge configuration failed"
        log_info "Transaction output: $TX_OUTPUT"
        exit 1
    fi
fi

log_info ""

# Fix WETH10 Bridge (optional, but check if needed)
log_fix "========================================="
log_fix "Checking WETH10 Bridge"
log_fix "========================================="

if [ -n "$WETH10_DEST" ] && ! echo "$WETH10_DEST" | grep -qE "^0x0+$"; then
    log_success "✓ WETH10 bridge already configured for Ethereum Mainnet"
    log_info "  Destination: $WETH10_DEST"
else
    log_warn "⚠ WETH10 bridge not configured for Ethereum Mainnet"
    log_info "  This is optional - only needed if bridging WETH10"
    log_info "  To configure, provide WETH10 Mainnet bridge address"
fi

log_info ""

# Verify fixes
log_info "========================================="
log_info "Verification"
log_info "========================================="

WETH9_DEST_FINAL=$(cast call "$WETH9_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")
WETH10_DEST_FINAL=$(cast call "$WETH10_BRIDGE" "destinations(uint64)" "$ETHEREUM_MAINNET_SELECTOR" --rpc-url "$RPC_URL" 2>/dev/null || echo "")

WETH9_DEST_FINAL_CLEAN=$(echo "$WETH9_DEST_FINAL" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")
WETH10_DEST_FINAL_CLEAN=$(echo "$WETH10_DEST_FINAL" | grep -oE "^0x[0-9a-fA-F]{40}$" | head -1 || echo "")

if [ -n "$WETH9_DEST_FINAL_CLEAN" ] && ! echo "$WETH9_DEST_FINAL_CLEAN" | grep -qE "^0x0+$" && [ "$WETH9_DEST_FINAL_CLEAN" != "0x0000000000000000000000000000000000000000" ]; then
    log_success "✓ WETH9 Bridge: Ethereum Mainnet configured"
    log_info "  Destination: $WETH9_DEST_FINAL_CLEAN"
else
    log_error "✗ WETH9 Bridge: Ethereum Mainnet NOT configured"
fi

if [ -n "$WETH10_DEST_FINAL_CLEAN" ] && ! echo "$WETH10_DEST_FINAL_CLEAN" | grep -qE "^0x0+$" && [ "$WETH10_DEST_FINAL_CLEAN" != "0x0000000000000000000000000000000000000000" ]; then
    log_success "✓ WETH10 Bridge: Ethereum Mainnet configured"
    log_info "  Destination: $WETH10_DEST_FINAL_CLEAN"
else
    log_warn "⚠ WETH10 Bridge: Ethereum Mainnet NOT configured (optional)"
fi

log_info ""

# Summary
log_info "========================================="
log_info "Summary"
log_info "========================================="

if [ -n "$WETH9_DEST_FINAL_CLEAN" ] && ! echo "$WETH9_DEST_FINAL_CLEAN" | grep -qE "^0x0+$" && [ "$WETH9_DEST_FINAL_CLEAN" != "0x0000000000000000000000000000000000000000" ]; then
    log_success "✓ All critical errors fixed!"
    log_info ""
    log_info "WETH9 bridge is now configured for Ethereum Mainnet"
    log_info "You can now bridge WETH9 to Ethereum Mainnet"
    log_info ""
    log_info "Next steps:"
    log_info "  1. Run dry run again to verify: ./scripts/dry-run-bridge-to-ethereum.sh [amount] [address]"
    log_info "  2. Bridge tokens: ./scripts/wrap-and-bridge-to-ethereum.sh [amount] [private_key]"
else
    log_error "✗ Errors not fully fixed"
    log_info ""
    log_info "WETH9 bridge still needs configuration"
    log_info "Make sure you provided the correct Ethereum Mainnet bridge address"
fi

log_info ""
