#!/usr/bin/env bash
# Generate prioritized deployment plan 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

# Color codes

echo "=== Prioritized Mainnet Deployment Plan ==="

# Get accurate costs
source <(./scripts/deployment/calculate-accurate-deployment-costs.sh 2>&1 | grep -E "^(export|TOTAL_COST|CONSERVATIVE)")

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

log_info "Current Status:"
echo "  Wallet Balance: $WALLET_BALANCE ETH"
echo "  Gas Price: $CONSERVATIVE_GAS Gwei"
echo "  Total Cost: $TOTAL_COST_ETH ETH"

# Contract information with costs
declare -A CONTRACT_COSTS=(
    ["CCIPLogger"]="$CCIPLogger_COST"
    ["CCIPWETH9Bridge"]="$CCIPWETH9Bridge_COST"
    ["CCIPWETH10Bridge"]="$CCIPWETH10Bridge_COST"
)

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

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_success "Remaining Contracts for Mainnet Deployment:"

# Sort by cost (cheapest first) for prioritization
ACCUMULATED_COST=0
PRIORITY=1
CAN_DEPLOY=()

for contract in $(printf '%s\n' "${!CONTRACT_COSTS[@]}" | while read c; do echo "$c ${CONTRACT_COSTS[$c]}"; done | sort -k2 -n | cut -d' ' -f1); 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")
    
    log_info "[Priority $PRIORITY] $contract"
    echo "  Cost: $cost ETH"
    echo "  Dependencies: $deps"
    echo "  Script: $script"
    
    if (( $(echo "$NEW_TOTAL <= $WALLET_BALANCE" | bc -l 2>/dev/null || echo "0") )); then
        echo -e "  Status: ${GREEN}✅ Can deploy${NC}"
        CAN_DEPLOY+=("$contract")
        ACCUMULATED_COST=$NEW_TOTAL
        PRIORITY=$((PRIORITY + 1))
    else
        NEEDED=$(echo "$cost - ($WALLET_BALANCE - $ACCUMULATED_COST)" | bc 2>/dev/null || echo "0")
        echo -e "  Status: ${RED}❌ Insufficient funds${NC}"
        echo "  Additional ETH needed: $NEEDED ETH"
    fi
done

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

log_warn "Summary:"
echo "  Contracts deployable: ${#CAN_DEPLOY[@]}/3"
echo "  Total cost (deployable): $ACCUMULATED_COST ETH"
echo "  Remaining balance: $REMAINING ETH"

if [ ${#CAN_DEPLOY[@]} -eq 0 ]; then
    log_error "⚠️  Cannot deploy any contracts with current balance"
    echo "  Fund wallet with at least $TOTAL_COST_ETH ETH to deploy all contracts"
elif [ ${#CAN_DEPLOY[@]} -lt 3 ]; then
    log_warn "⚠️  Can only deploy ${#CAN_DEPLOY[@]} of 3 contracts"
    echo "  Fund wallet with additional ETH to deploy remaining contracts"
else
    log_success "✅ Can deploy all contracts"
fi
