#!/usr/bin/env bash

# Get wallet address from private key in .env file

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
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:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

log_info "=== Wallet Address from .env Private Key ==="

# Check if cast is available
if ! command -v cast &> /dev/null; then
    log_error "Error: cast (Foundry) not found. Please install Foundry."
    exit 1
fi

# Get private key from .env
if ! require_private_key_env; then
    exit 1
fi

# Derive address
WALLET_ADDRESS="$(derive_deployer_address || true)"

if [ -z "$WALLET_ADDRESS" ]; then
    log_error "ERROR: Could not derive DEPLOYER_ADDRESS from PRIVATE_KEY."
    exit 1
fi

log_success "Wallet Address: $WALLET_ADDRESS"

# Show funding requirements
log_info "=== Funding Requirements ==="
log_warn "Ethereum Mainnet:"
echo "  Minimum: 0.025 ETH"
echo "  Recommended: 0.05 ETH (with buffer)"
echo "  Purpose: Gas fees for bridge deployment"
log_warn "ChainID 138:"
echo "  Minimum: 1 ETH"
echo "  Recommended: 2 ETH (with buffer)"
echo "  Purpose: Gas fees for bridge deployment"

# Show balances if RPC is available
RPC_URL="${RPC_URL:-${RPC_URL_138:-${CHAIN138_RPC_URL:-}}}"
MAINNET_RPC_URL="${MAINNET_RPC_URL:-${ETHEREUM_MAINNET_RPC:-}}"
if [ -n "$RPC_URL" ]; then
    log_info "=== Current Balances ==="
    
    # Check Mainnet balance
    MAINNET_RPC="${MAINNET_RPC_URL:-https://eth.llamarpc.com}"
    
    MAINNET_BALANCE=$(cast balance "$WALLET_ADDRESS" --rpc-url "$MAINNET_RPC" 2>/dev/null || echo "0")
    MAINNET_ETH=$(cast --to-unit "$MAINNET_BALANCE" ether 2>/dev/null || echo "0")
    echo -e "Mainnet ETH: ${GREEN}$MAINNET_ETH ETH${NC}"
    
    # Check ChainID 138 balance
    CHAIN138_BALANCE=$(cast balance "$WALLET_ADDRESS" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
    CHAIN138_ETH=$(cast --to-unit "$CHAIN138_BALANCE" ether 2>/dev/null || echo "0")
    echo -e "ChainID 138 ETH: ${GREEN}$CHAIN138_ETH ETH${NC}"
fi

log_info "=== Quick Copy ==="
echo "Wallet Address:"
echo "$WALLET_ADDRESS"
echo "Copy this address to fund your wallet for deployment."
