#!/usr/bin/env bash
# Prioritize Mainnet deployments based on wallet balance

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
source "$SCRIPT_DIR/../lib/init.sh"
source "$PROJECT_ROOT/scripts/load-env.sh" >/dev/null 2>&1 || true

echo "=== Mainnet Deployment Prioritization ==="

# Color codes

# Get wallet balance
WALLET_BALANCE=$(./scripts/deployment/check-mainnet-balances.sh 2>&1 | grep -oP 'Balance: \K[0-9.]+' | head -1)

# Get gas prices
source <(./scripts/deployment/get-mainnet-gas-prices.sh 2>&1 | grep -E "^(export|CONSERVATIVE)")

# Contract deployment costs (in ETH, estimated)
declare -A CONTRACT_COSTS=(
    ["CCIPLogger"]=0.008
    ["CCIPWETH9Bridge"]=0.006
    ["CCIPWETH10Bridge"]=0.006
)

# Contract dependencies
declare -A CONTRACT_DEPS=(
    ["CCIPLogger"]="None"
    ["CCIPWETH9Bridge"]="CCIPRouter"
    ["CCIPWETH10Bridge"]="CCIPRouter"
)

# Contract deployment scripts
declare -A CONTRACT_SCRIPTS=(
    ["CCIPLogger"]="npx hardhat run scripts/ccip-deployment/deploy-ccip-logger.js --network mainnet"
    ["CCIPWETH9Bridge"]="bash scripts/forge/scope.sh script ccip script/DeployCCIPWETH9Bridge.s.sol:DeployCCIPWETH9Bridge --rpc-url \$ETHEREUM_MAINNET_RPC --broadcast --private-key \$PRIVATE_KEY"
    ["CCIPWETH10Bridge"]="bash scripts/forge/scope.sh script ccip script/DeployCCIPWETH10Bridge.s.sol:DeployCCIPWETH10Bridge --rpc-url \$ETHEREUM_MAINNET_RPC --broadcast --private-key \$PRIVATE_KEY"
)

log_info "Wallet Balance: $WALLET_BALANCE ETH"
log_info "Gas Price: $CONSERVATIVE_GAS Gwei"

# Calculate what can be deployed
log_success "Deployment Priority (based on available balance):"

ACCUMULATED_COST=0
PRIORITY=1

# Sort contracts by cost (cheapest first)
for contract in $(printf '%s\n' "${!CONTRACT_COSTS[@]}" | sort -k2 -n); do
    cost="${CONTRACT_COSTS[$contract]}"
    deps="${CONTRACT_DEPS[$contract]}"
    script="${CONTRACT_SCRIPTS[$contract]}"
    
    NEW_TOTAL=$(echo "$ACCUMULATED_COST + $cost" | bc 2>/dev/null || echo "0")
    
    if (( $(echo "$NEW_TOTAL <= $WALLET_BALANCE" | bc -l 2>/dev/null || echo "0") )); then
        log_success "[Priority $PRIORITY] $contract"
        echo "  Cost: $cost ETH"
        echo "  Dependencies: $deps"
        echo "  Command: $script"
        echo "  Status: ✅ Can deploy"
        ACCUMULATED_COST=$NEW_TOTAL
        PRIORITY=$((PRIORITY + 1))
    else
        NEEDED=$(echo "$cost - ($WALLET_BALANCE - $ACCUMULATED_COST)" | bc 2>/dev/null || echo "0")
        log_error "[Blocked] $contract"
        echo "  Cost: $cost ETH"
        echo "  Dependencies: $deps"
        echo "  Status: ❌ Insufficient funds"
        echo "  Additional ETH needed: $NEEDED ETH"
    fi
done

REMAINING=$(echo "$WALLET_BALANCE - $ACCUMULATED_COST" | bc 2>/dev/null || echo "0")

log_warn "Summary:"
echo "  Total balance: $WALLET_BALANCE ETH"
echo "  Total cost (deployable): $ACCUMULATED_COST ETH"
echo "  Remaining after deployments: $REMAINING ETH"

if (( $(echo "$REMAINING < 0" | bc -l 2>/dev/null || echo "1") )); then
    log_error "⚠️  Insufficient balance for all deployments"
    echo "  Fund wallet with additional ETH to deploy all contracts"
else
    log_success "✅ Sufficient balance for prioritized deployments"
fi
