#!/usr/bin/env bash
# Bridge 100 ETH to Ethereum Mainnet
# This script will check prerequisites and bridge 100 ETH

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'
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_step() { echo -e "${CYAN}[STEP]${NC} $1"; }

load_explorer_runtime_env

# Check for private key
if [ -z "${PRIVATE_KEY:-}" ]; then
    log_error "PRIVATE_KEY not available in effective environment"
    log_info ""
    log_info "Please export your private key before running:"
    log_info "  export PRIVATE_KEY=0x..."
    log_info ""
    log_info "Or provide it as an argument:"
    log_info "  $0 [private_key]"
    log_info ""
    exit 1
fi

# Check if private key is provided as argument (override .env)
if [ -n "${1:-}" ]; then
    PRIVATE_KEY="$1"
    log_info "Using private key from argument"
fi

# Validate private key
ADDR=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")
if [ -z "$ADDR" ]; then
    log_error "Invalid private key"
    exit 1
fi

log_success "✓ Private key validated"
log_info "  Address: $ADDR"
log_info ""

# Check bridge configuration
log_step "Checking bridge configuration..."
ETHEREUM_CONFIGURED=$("$SCRIPT_DIR/check-bridge-config.sh" 2>&1 | grep -c "Ethereum.*CONFIGURED" || echo "0")

if [ "$ETHEREUM_CONFIGURED" = "0" ]; then
    log_warn "⚠ Ethereum Mainnet bridge is NOT configured"
    log_info ""
    log_info "You need to configure the bridge destination first."
    log_info "This requires the Ethereum Mainnet bridge address."
    log_info ""
    log_info "To configure:"
    log_info "  ./scripts/fix-bridge-errors.sh [private_key] [ethereum_mainnet_bridge_address]"
    log_info ""
    read -p "Do you want to continue anyway? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        log_info "Aborted by user"
        exit 1
    fi
    log_warn "Proceeding without bridge configuration check..."
else
    log_success "✓ Ethereum Mainnet bridge is configured"
fi

log_info ""

# Proceed with bridging 100 ETH
log_step "Bridging 100 ETH to Ethereum Mainnet..."
log_info ""

"$SCRIPT_DIR/wrap-and-bridge-to-ethereum.sh" 100 "$PRIVATE_KEY"
