#!/usr/bin/env bash
# Fund new deployer account to bypass stuck transaction
# Usage: ./fund-new-deployer-account.sh [amount_in_ether]

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

# Load environment variables
if [ -f "$SOURCE_PROJECT/.env" ]; then
    source "$SOURCE_PROJECT/.env"
else
    log_error ".env file not found in $SOURCE_PROJECT"
    exit 1
fi

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
OLD_DEPLOYER=$(cast wallet address --private-key "$PRIVATE_KEY" 2>/dev/null || echo "")

if [ -z "$OLD_DEPLOYER" ]; then
    log_error "Failed to get old deployer address"
    exit 1
fi

# New account address (from previous investigation)
NEW_DEPLOYER="0xC13EfAe66708C7541d2D66A2527bcBF9992e7186"
AMOUNT="${1:-10}"  # Default 10 ETH

log_info "========================================="
log_info "Fund New Deployer Account"
log_info "========================================="
log_info ""
log_info "Old Deployer: $OLD_DEPLOYER"
log_info "New Deployer: $NEW_DEPLOYER"
log_info "Amount: $AMOUNT ETH"
log_info "RPC URL: $RPC_URL"
log_info ""

# Check old deployer balance
log_info "Checking old deployer balance..."
OLD_BALANCE=$(cast balance "$OLD_DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
OLD_BALANCE_ETH=$(echo "scale=4; $OLD_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
log_info "Old deployer balance: $OLD_BALANCE_ETH ETH"

if (( $(echo "$OLD_BALANCE_ETH < $AMOUNT" | bc -l 2>/dev/null || echo "1") )); then
    log_error "Insufficient balance. Need $AMOUNT ETH, have $OLD_BALANCE_ETH ETH"
    exit 1
fi

# Check new deployer balance
log_info "Checking new deployer balance..."
NEW_BALANCE=$(cast balance "$NEW_DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
NEW_BALANCE_ETH=$(echo "scale=4; $NEW_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
log_info "New deployer balance: $NEW_BALANCE_ETH ETH"

if (( $(echo "$NEW_BALANCE_ETH >= $AMOUNT" | bc -l 2>/dev/null || echo "0") )); then
    log_success "✓ New account already has sufficient balance"
    exit 0
fi

# Calculate amount in wei
AMOUNT_WEI=$(echo "$AMOUNT * 1000000000000000000" | bc 2>/dev/null || echo "0")

# Get current gas price and use higher value
CURRENT_GAS=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
HIGH_GAS=$(echo "$CURRENT_GAS * 10" | bc 2>/dev/null || echo "10000000000")  # 10x current gas price
log_info "Using gas price: $(echo "scale=2; $HIGH_GAS / 1000000000" | bc) gwei"

# Send funds
log_info "Sending $AMOUNT ETH to new deployer..."
TX_OUTPUT=$(cast send "$NEW_DEPLOYER" \
    --value "$AMOUNT_WEI" \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --gas-price "$HIGH_GAS" \
    --gas-limit 21000 \
    2>&1 || echo "FAILED")

if echo "$TX_OUTPUT" | grep -qE "transactionHash|Success"; then
    HASH=$(echo "$TX_OUTPUT" | grep -oE "transactionHash[[:space:]]+0x[0-9a-fA-F]{64}" | awk '{print $2}' || echo "")
    if [ -n "$HASH" ]; then
        log_success "✓ Funds sent: $HASH"
        log_info "Waiting for transaction to be mined..."
        sleep 10
        
        # Verify new balance
        NEW_BALANCE=$(cast balance "$NEW_DEPLOYER" --rpc-url "$RPC_URL" 2>/dev/null || echo "0")
        NEW_BALANCE_ETH=$(echo "scale=4; $NEW_BALANCE / 1000000000000000000" | bc 2>/dev/null || echo "0")
        log_success "✓ New deployer balance: $NEW_BALANCE_ETH ETH"
    else
        log_warn "⚠ Transaction sent but hash not found"
    fi
else
    ERR=$(echo "$TX_OUTPUT" | grep -E "Error|reverted" | head -1 || echo "Unknown")
    log_error "✗ Failed to send funds: $ERR"
    log_info "Full output: $TX_OUTPUT"
    exit 1
fi

log_info ""
log_success "========================================="
log_success "Funding Complete"
log_success "========================================="
log_info ""
log_info "Next steps:"
log_info "  1. Update .env with new PRIVATE_KEY"
log_info "  2. Run: ./scripts/configure-ethereum-mainnet-with-new-account.sh"

