#!/usr/bin/env bash
# Cost calculation library
# Usage: source "$SCRIPT_DIR/lib/deployment/costs.sh"

# Source libraries (use absolute path resolution)
LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
[ -z "${PROJECT_ROOT:-}" ] && source "${LIB_DIR}/../common/paths.sh"
[ -z "${log_info:-}" ] && source "${LIB_DIR}/../common/logging.sh"

# Check for required commands
command_exists() {
    command -v "$1" &> /dev/null
}

# Default gas requirements (in wei units, can be overridden)
DEFAULT_CCIPWETH9_BRIDGE_GAS="${CCIPWETH9_BRIDGE_GAS:-263000}"
DEFAULT_CCIPWETH10_BRIDGE_GAS="${CCIPWETH10_BRIDGE_GAS:-263000}"
DEFAULT_CONFIGURATION_GAS="${CONFIGURATION_GAS:-200000}"

# Load environment variables
load_env_file() {
    local env_file="${PROJECT_ROOT}/.env"
    if [ -f "$env_file" ]; then
        set -a
        source "$env_file"
        set +a
    fi
}

# Get gas price from multiple sources
get_gas_price() {
    local source_type="${1:-auto}"  # auto, rpc, infura, default, conservative
    
    load_env_file
    
    local gas_price_wei=""
    local gas_price_gwei=""
    local source_name=""
    
    case "$source_type" in
        rpc|auto)
            # Try ETHEREUM_MAINNET_RPC
            if [ -n "${ETHEREUM_MAINNET_RPC:-}" ]; then
                if command_exists cast; then
                    gas_price_wei=$(cast gas-price --rpc-url "$ETHEREUM_MAINNET_RPC" 2>/dev/null || echo "")
                    if [ -n "$gas_price_wei" ] && [ "$gas_price_wei" != "0" ]; then
                        gas_price_gwei=$(cast --to-unit "$gas_price_wei" gwei 2>/dev/null || echo "")
                        source_name="ETHEREUM_MAINNET_RPC"
                    fi
                fi
            fi
            ;;
        infura|auto)
            # Try Infura Gas API
            if [ -z "$gas_price_wei" ] && [ -n "${INFURA_GAS_API:-}" ]; then
                local api_key="$INFURA_GAS_API"
                # Extract API key from URL if needed
                if [[ "$INFURA_GAS_API" == *"infura.io"* ]]; then
                    api_key=$(echo "$INFURA_GAS_API" | sed -n 's|.*/v3/\(.*\)|\1|p')
                fi
                
                if [ -n "$api_key" ] && command_exists curl && command_exists jq; then
                    local response=$(curl -s "https://gas.api.infura.io/networks/1/suggestedGasFees" \
                        -H "Authorization: Basic $(echo -n :$api_key | base64)" 2>/dev/null || echo "")
                    
                    if [ -n "$response" ]; then
                        local standard_gas=$(echo "$response" | jq -r '.standard.maxFeePerGas' 2>/dev/null || echo "")
                        if [ -n "$standard_gas" ] && [ "$standard_gas" != "null" ] && [ "$standard_gas" != "" ]; then
                            gas_price_wei="$standard_gas"
                            if command_exists cast; then
                                gas_price_gwei=$(cast --to-unit "$gas_price_wei" gwei 2>/dev/null || echo "")
                            else
                                gas_price_gwei=$(echo "scale=2; $gas_price_wei / 1000000000" | bc 2>/dev/null || echo "")
                            fi
                            source_name="Infura Gas API"
                        fi
                    fi
                fi
            fi
            ;;
        default|auto)
            # Fallback to default RPC
            if [ -z "$gas_price_wei" ] && command_exists cast; then
                gas_price_wei=$(cast gas-price --rpc-url "https://eth.llamarpc.com" 2>/dev/null || echo "")
                if [ -n "$gas_price_wei" ] && [ "$gas_price_wei" != "0" ]; then
                    gas_price_gwei=$(cast --to-unit "$gas_price_wei" gwei 2>/dev/null || echo "")
                    source_name="Default RPC"
                fi
            fi
            ;;
        conservative)
            # Use conservative estimate (50% above current)
            gas_price_wei=$(get_gas_price "auto")
            if [ -n "$gas_price_wei" ] && [ "$gas_price_wei" != "0" ]; then
                gas_price_wei=$(echo "$gas_price_wei * 1.5" | bc 2>/dev/null || echo "$gas_price_wei")
                if command_exists cast; then
                    gas_price_gwei=$(cast --to-unit "$gas_price_wei" gwei 2>/dev/null || echo "")
                else
                    gas_price_gwei=$(echo "scale=2; $gas_price_wei / 1000000000" | bc 2>/dev/null || echo "")
                fi
                source_name="Conservative Estimate"
            fi
            ;;
    esac
    
    # Final fallback
    if [ -z "$gas_price_wei" ] || [ "$gas_price_wei" = "0" ]; then
        gas_price_gwei="${DEFAULT_GAS_PRICE_GWEI:-30}"
        gas_price_wei=$(echo "$gas_price_gwei * 1000000000" | bc 2>/dev/null || echo "30000000000")
        source_name="Fallback Default"
    fi
    
    echo "$gas_price_wei|$gas_price_gwei|$source_name"
}

# Calculate cost in ETH
calculate_cost_eth() {
    local gas=$1
    local gas_price_wei=$2
    
    local cost_wei=$(echo "$gas * $gas_price_wei" | bc 2>/dev/null || echo "0")
    local cost_eth=$(echo "scale=10; $cost_wei / 1000000000000000000" | bc 2>/dev/null || echo "0")
    
    echo "$cost_eth"
}

# Calculate cost in USD
calculate_cost_usd() {
    local cost_eth=$1
    local eth_price_usd="${2:-${ETH_PRICE_USD:-2500}}"
    
    local cost_usd=$(echo "scale=2; $cost_eth * $eth_price_usd" | bc 2>/dev/null || echo "0")
    echo "$cost_usd"
}

# Format cost output
format_cost_output() {
    local item_name="$1"
    local cost_eth="$2"
    local cost_usd="$3"
    
    printf "%-30s %18.8f ETH  $%15.2f\n" "$item_name" "$cost_eth" "$cost_usd"
}

# Get ETH price (simple version, can be enhanced)
get_eth_price() {
    local eth_price="${ETH_PRICE_USD:-2500}"
    echo "$eth_price"
}

