#!/usr/bin/env bash
# Get Optimal Gas Price from Etherscan Gas API
# Provides Safe, Proposed, and Fast gas prices
# Usage: ./get-optimal-gas-from-api.sh [speed] [chain_id]
# Speed: safe, proposed, fast (default: proposed)
# Chain ID: 1 for Ethereum Mainnet (default: uses RPC chain)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
elif [ -f "$PROJECT_ROOT/../.env" ]; then
    source "$PROJECT_ROOT/../.env"
fi

# Configuration
SPEED="${1:-proposed}"  # safe, proposed, fast
CHAIN_ID="${2:-}"
RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"

# Get chain ID from RPC if not provided
if [ -z "$CHAIN_ID" ]; then
    CHAIN_ID=$(cast chain-id --rpc-url "$RPC_URL" 2>/dev/null || echo "1")
fi

# Etherscan API endpoints by chain
declare -A ETHERSCAN_APIS=(
    ["1"]="https://api.etherscan.io/api"
    ["56"]="https://api.bscscan.com/api"
    ["137"]="https://api.polygonscan.com/api"
    ["43114"]="https://api.snowtrace.io/api"
    ["8453"]="https://api.basescan.org/api"
    ["42161"]="https://api.arbiscan.io/api"
    ["10"]="https://api-optimistic.etherscan.io/api"
)

# Get API endpoint
API_ENDPOINT="${ETHERSCAN_APIS[$CHAIN_ID]:-}"
if [ -z "$API_ENDPOINT" ]; then
    # Fallback to RPC gas price for unsupported chains
    GAS_PRICE=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    echo "$GAS_PRICE"
    exit 0
fi

# Get API key (optional, works without it but with rate limits)
API_KEY="${ETHERSCAN_API_KEY:-}"

# Build API URL
if [ -n "$API_KEY" ]; then
    API_URL="${API_ENDPOINT}?module=gastracker&action=gasoracle&apikey=${API_KEY}"
else
    API_URL="${API_ENDPOINT}?module=gastracker&action=gasoracle"
fi

# Fetch gas prices from API
GAS_DATA=$(curl -s "$API_URL" 2>/dev/null || echo "")

if [ -z "$GAS_DATA" ]; then
    # Fallback to RPC gas price
    GAS_PRICE=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
    echo "$GAS_PRICE"
    exit 0
fi

# Parse gas price based on speed
case "$SPEED" in
    safe)
        GAS_PRICE_GWEI=$(echo "$GAS_DATA" | grep -oE '"SafeGasPrice":"[0-9.]+"' | cut -d'"' -f4 || echo "")
        ;;
    proposed)
        GAS_PRICE_GWEI=$(echo "$GAS_DATA" | grep -oE '"ProposeGasPrice":"[0-9.]+"' | cut -d'"' -f4 || echo "")
        ;;
    fast)
        GAS_PRICE_GWEI=$(echo "$GAS_DATA" | grep -oE '"FastGasPrice":"[0-9.]+"' | cut -d'"' -f4 || echo "")
        ;;
    *)
        GAS_PRICE_GWEI=$(echo "$GAS_DATA" | grep -oE '"ProposeGasPrice":"[0-9.]+"' | cut -d'"' -f4 || echo "")
        ;;
esac

# Convert Gwei to Wei
if [ -n "$GAS_PRICE_GWEI" ] && [ "$GAS_PRICE_GWEI" != "0" ]; then
    # Convert decimal Gwei to Wei (multiply by 1e9)
    GAS_PRICE=$(echo "scale=0; $GAS_PRICE_GWEI * 1000000000 / 1" | bc 2>/dev/null || echo "")
    
    if [ -n "$GAS_PRICE" ] && [ "$GAS_PRICE" != "0" ]; then
        echo "$GAS_PRICE"
        exit 0
    fi
fi

# Fallback to RPC gas price
GAS_PRICE=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
echo "$GAS_PRICE"

