#!/usr/bin/env bash
# Final comprehensive Mainnet deployment report

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 "==================================================================="
echo "  MAINNET DEPLOYMENT COMPREHENSIVE REPORT"
echo "==================================================================="

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

# Get gas prices
GAS_JSON=$(curl -s "https://api.etherscan.io/v2/api?chainid=1&module=gastracker&action=gasoracle&apikey=${ETHERSCAN_API_KEY}")
FAST_GAS=$(echo "$GAS_JSON" | python3 -c "import sys, json; print(json.load(sys.stdin)['result']['FastGasPrice'])" 2>/dev/null)
CONSERVATIVE_GAS=$(echo "$FAST_GAS * 2.5" | bc 2>/dev/null)
CONSERVATIVE_GAS_WEI=$(echo "$CONSERVATIVE_GAS * 1000000000" | bc 2>/dev/null)

log_info "📊 CURRENT STATUS"
echo "  Wallet Address: 0x4A666F96fC8764181194447A7dFdb7d471b301C8"
echo "  Wallet Balance: $WALLET_BALANCE ETH"
echo "  Current Gas (Fast): $FAST_GAS Gwei"
echo "  Recommended Gas (2.5x): $CONSERVATIVE_GAS Gwei"

log_info "📋 REMAINING SMART CONTRACTS FOR MAINNET"

# Contract details
declare -A CONTRACT_GAS=(
    ["CCIPLogger"]=2500000
    ["CCIPWETH9Bridge"]=1800000
    ["CCIPWETH10Bridge"]=1800000
)

declare -A CONTRACT_FRAMEWORK=(
    ["CCIPLogger"]="Hardhat"
    ["CCIPWETH9Bridge"]="Foundry"
    ["CCIPWETH10Bridge"]="Foundry"
)

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"
)

TOTAL_COST_WEI=0
declare -A COSTS

echo "1. CCIPLogger"
echo "   Location: contracts/ccip-integration/CCIPLogger.sol"
echo "   Framework: Hardhat"
echo "   Gas Units: 2,500,000"
gas_units=2500000
cost_wei=$(echo "$gas_units * $CONSERVATIVE_GAS_WEI" | bc 2>/dev/null)
cost_eth=$(echo "scale=10; $cost_wei / 1000000000000000000" | bc 2>/dev/null)
COSTS["CCIPLogger"]=$cost_eth
TOTAL_COST_WEI=$(echo "$TOTAL_COST_WEI + $cost_wei" | bc 2>/dev/null)
echo "   Estimated Cost: $cost_eth ETH"
echo "   Dependencies: None"
echo "   Script: npx hardhat run scripts/ccip-deployment/deploy-ccip-logger.js --network mainnet"

echo "2. CCIPWETH9Bridge"
echo "   Location: contracts/ccip/CCIPWETH9Bridge.sol"
echo "   Framework: Foundry"
echo "   Gas Units: 1,800,000"
gas_units=1800000
cost_wei=$(echo "$gas_units * $CONSERVATIVE_GAS_WEI" | bc 2>/dev/null)
cost_eth=$(echo "scale=10; $cost_wei / 1000000000000000000" | bc 2>/dev/null)
COSTS["CCIPWETH9Bridge"]=$cost_eth
TOTAL_COST_WEI=$(echo "$TOTAL_COST_WEI + $cost_wei" | bc 2>/dev/null)
echo "   Estimated Cost: $cost_eth ETH"
echo "   Dependencies: CCIPRouter"
echo "   Script: bash scripts/forge/scope.sh script ccip script/DeployCCIPWETH9Bridge.s.sol:DeployCCIPWETH9Bridge --rpc-url \$ETHEREUM_MAINNET_RPC --broadcast --private-key \$PRIVATE_KEY"

echo "3. CCIPWETH10Bridge"
echo "   Location: contracts/ccip/CCIPWETH10Bridge.sol"
echo "   Framework: Foundry"
echo "   Gas Units: 1,800,000"
gas_units=1800000
cost_wei=$(echo "$gas_units * $CONSERVATIVE_GAS_WEI" | bc 2>/dev/null)
cost_eth=$(echo "scale=10; $cost_wei / 1000000000000000000" | bc 2>/dev/null)
COSTS["CCIPWETH10Bridge"]=$cost_eth
TOTAL_COST_WEI=$(echo "$TOTAL_COST_WEI + $cost_wei" | bc 2>/dev/null)
echo "   Estimated Cost: $cost_eth ETH"
echo "   Dependencies: CCIPRouter"
echo "   Script: bash scripts/forge/scope.sh script ccip script/DeployCCIPWETH10Bridge.s.sol:DeployCCIPWETH10Bridge --rpc-url \$ETHEREUM_MAINNET_RPC --broadcast --private-key \$PRIVATE_KEY"

TOTAL_COST_ETH=$(echo "scale=10; $TOTAL_COST_WEI / 1000000000000000000" | bc 2>/dev/null)

log_info "💰 COST SUMMARY"
echo "  CCIPLogger: ${COSTS[CCIPLogger]} ETH"
echo "  CCIPWETH9Bridge: ${COSTS[CCIPWETH9Bridge]} ETH"
echo "  CCIPWETH10Bridge: ${COSTS[CCIPWETH10Bridge]} ETH"
echo "  ─────────────────────────────"
echo "  Total Cost: $TOTAL_COST_ETH ETH"
echo "  Wallet Balance: $WALLET_BALANCE ETH"

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

if (( $(echo "$WALLET_BALANCE >= $TOTAL_COST_ETH" | bc -l 2>/dev/null || echo "0") )); then
    log_success "✅ SUFFICIENT FUNDS FOR ALL DEPLOYMENTS"
    echo "  Remaining after deployments: $REMAINING ETH"
    log_success "🎯 PRIORITIZED DEPLOYMENT ORDER"
    echo "  [Priority 1] CCIPLogger"
    echo "    Cost: ${COSTS[CCIPLogger]} ETH"
    echo "    Status: ✅ Can deploy"
    echo "    Remaining after: $(echo "$WALLET_BALANCE - ${COSTS[CCIPLogger]}" | bc) ETH"
    
    after_logger=$(echo "$WALLET_BALANCE - ${COSTS[CCIPLogger]}" | bc 2>/dev/null)
    if (( $(echo "$after_logger >= ${COSTS[CCIPWETH9Bridge]}" | bc -l 2>/dev/null || echo "0") )); then
        echo "  [Priority 2] CCIPWETH9Bridge"
        echo "    Cost: ${COSTS[CCIPWETH9Bridge]} ETH"
        echo "    Status: ✅ Can deploy (after CCIPRouter configured)"
        echo "    Remaining after: $(echo "$after_logger - ${COSTS[CCIPWETH9Bridge]}" | bc) ETH"
        
        after_bridge9=$(echo "$after_logger - ${COSTS[CCIPWETH9Bridge]}" | bc 2>/dev/null)
        if (( $(echo "$after_bridge9 >= ${COSTS[CCIPWETH10Bridge]}" | bc -l 2>/dev/null || echo "0") )); then
            echo "  [Priority 3] CCIPWETH10Bridge"
            echo "    Cost: ${COSTS[CCIPWETH10Bridge]} ETH"
            echo "    Status: ✅ Can deploy (after CCIPRouter configured)"
            echo "    Remaining after: $(echo "$after_bridge9 - ${COSTS[CCIPWETH10Bridge]}" | bc) ETH"
        else
            echo "  [Priority 3] CCIPWETH10Bridge"
            echo "    Cost: ${COSTS[CCIPWETH10Bridge]} ETH"
            echo "    Status: ❌ Insufficient funds"
            echo "    Additional needed: $(echo "${COSTS[CCIPWETH10Bridge]} - $after_bridge9" | bc) ETH"
        fi
    else
        echo "  [Priority 2] CCIPWETH9Bridge"
        echo "    Cost: ${COSTS[CCIPWETH9Bridge]} ETH"
        echo "    Status: ❌ Insufficient funds"
        echo "    Additional needed: $(echo "${COSTS[CCIPWETH9Bridge]} - $after_logger" | bc) ETH"
        echo "  [Priority 3] CCIPWETH10Bridge"
        echo "    Cost: ${COSTS[CCIPWETH10Bridge]} ETH"
        echo "    Status: ❌ Insufficient funds"
    fi
else
    NEEDED=$(echo "$TOTAL_COST_ETH - $WALLET_BALANCE" | bc 2>/dev/null)
    log_error "❌ INSUFFICIENT FUNDS"
    echo "  Additional ETH needed: $NEEDED ETH"
    log_warn "⚠️  Prioritized deployment order (based on available balance):"
    
    if (( $(echo "$WALLET_BALANCE >= ${COSTS[CCIPLogger]}" | bc -l 2>/dev/null || echo "0") )); then
        echo "  [Priority 1] CCIPLogger"
        echo "    Cost: ${COSTS[CCIPLogger]} ETH"
        echo "    Status: ✅ Can deploy"
        after_logger=$(echo "$WALLET_BALANCE - ${COSTS[CCIPLogger]}" | bc 2>/dev/null)
        
        if (( $(echo "$after_logger >= ${COSTS[CCIPWETH9Bridge]}" | bc -l 2>/dev/null || echo "0") )); then
            echo "  [Priority 2] CCIPWETH9Bridge"
            echo "    Cost: ${COSTS[CCIPWETH9Bridge]} ETH"
            echo "    Status: ✅ Can deploy"
            after_bridge9=$(echo "$after_logger - ${COSTS[CCIPWETH9Bridge]}" | bc 2>/dev/null)
            
            if (( $(echo "$after_bridge9 >= ${COSTS[CCIPWETH10Bridge]}" | bc -l 2>/dev/null || echo "0") )); then
                echo "  [Priority 3] CCIPWETH10Bridge"
                echo "    Cost: ${COSTS[CCIPWETH10Bridge]} ETH"
                echo "    Status: ✅ Can deploy"
            else
                echo "  [Priority 3] CCIPWETH10Bridge"
                echo "    Cost: ${COSTS[CCIPWETH10Bridge]} ETH"
                echo "    Status: ❌ Insufficient funds"
            fi
        else
            echo "  [Priority 2] CCIPWETH9Bridge"
            echo "    Cost: ${COSTS[CCIPWETH9Bridge]} ETH"
            echo "    Status: ❌ Insufficient funds"
            echo "  [Priority 3] CCIPWETH10Bridge"
            echo "    Cost: ${COSTS[CCIPWETH10Bridge]} ETH"
            echo "    Status: ❌ Insufficient funds"
        fi
    else
        echo "  [Priority 1] CCIPLogger"
        echo "    Cost: ${COSTS[CCIPLogger]} ETH"
        echo "    Status: ❌ Insufficient funds"
        echo "    Additional needed: $(echo "${COSTS[CCIPLogger]} - $WALLET_BALANCE" | bc) ETH"
        echo "  [Priority 2] CCIPWETH9Bridge"
        echo "    Cost: ${COSTS[CCIPWETH9Bridge]} ETH"
        echo "    Status: ❌ Insufficient funds"
        echo "  [Priority 3] CCIPWETH10Bridge"
        echo "    Cost: ${COSTS[CCIPWETH10Bridge]} ETH"
        echo "    Status: ❌ Insufficient funds"
    fi
fi

log_info "📝 NEXT STEPS"
echo "  1. Compile contracts: ./scripts/deployment/compile-test-mainnet-contracts.sh"
echo "  2. Check gas prices: ./scripts/deployment/get-mainnet-gas-prices.sh"
echo "  3. Deploy in priority order (see above)"
echo "==================================================================="
