#!/usr/bin/env bash
# Get real-time gas prices for all chains (Mainnet, Cronos, BSC, Polygon, Gnosis)
# Updates gas estimates in documentation using API data from .env
#
# Usage:
#   ./scripts/deployment/get-multichain-gas-prices.sh
#
# Requires:
#   - .env file with ETHERSCAN_API_KEY and RPC URLs
#   - cast (Foundry) for RPC calls
#   - bc for calculations
#   - curl for API calls
#
# Output:
#   - Displays gas prices and costs for all chains
#   - Exports environment variables
#   - Saves JSON to /tmp/multichain_gas_prices.json

set -euo pipefail

# Source environment variables
if [ -f .env ]; then
    set -a
    source .env
    set +a
fi

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Gas price conversion (wei to gwei)
wei_to_gwei() {
    local wei=$1
    echo "scale=2; $wei / 1000000000" | bc
}

# Get Ethereum Mainnet gas price
get_eth_gas_price() {
    local gas_price_wei=""

    # Try Etherscan API first
    if [ -n "${ETHERSCAN_API_KEY:-}" ]; then
        local response=$(curl -s "https://api.etherscan.io/v2/api?chainid=1&module=gastracker&action=gasoracle&apikey=${ETHERSCAN_API_KEY}" 2>/dev/null)
        if [ $? -eq 0 ] && echo "$response" | grep -q "FastGasPrice"; then
            # Try jq first (more reliable)
            if command -v jq >/dev/null 2>&1; then
                local gas_price_gwei=$(echo "$response" | jq -r '.result.FastGasPrice' 2>/dev/null)
                if [ -n "$gas_price_gwei" ] && [ "$gas_price_gwei" != "null" ] && [ "$gas_price_gwei" != "" ]; then
                    # Etherscan returns in gwei (decimal), convert to wei
                    gas_price_wei=$(echo "scale=0; $gas_price_gwei * 1000000000 / 1" | bc 2>/dev/null)
                    if [ -n "$gas_price_wei" ] && [ "$gas_price_wei" != "0" ]; then
                        echo "$gas_price_wei"
                        return 0
                    fi
                fi
            fi
            # Fallback to grep
            local gas_price_gwei=$(echo "$response" | grep -o '"FastGasPrice":"[^"]*"' | cut -d'"' -f4)
            if [ -n "$gas_price_gwei" ]; then
                # Convert gwei to wei
                gas_price_wei=$(echo "scale=0; $gas_price_gwei * 1000000000 / 1" | bc 2>/dev/null)
                if [ -n "$gas_price_wei" ] && [ "$gas_price_wei" != "0" ]; then
                    echo "$gas_price_wei"
                    return 0
                fi
            fi
        fi
    fi

    # Try RPC endpoint
    if [ -n "${ETH_MAINNET_RPC_URL:-}" ]; then
        gas_price_wei=$(cast gas-price --rpc-url "$ETH_MAINNET_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi

    # Fallback to default
    echo "20000000000"  # 20 gwei default
}

# Get Cronos gas price
get_cronos_gas_price() {
    if [ -n "${CRONOS_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$CRONOS_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "1000000000"  # 1 gwei default (1000 gwei in Cronos terms)
}

# Get BSC gas price
get_bsc_gas_price() {
    if [ -n "${BSC_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$BSC_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "5000000000"  # 5 gwei default
}

# Get Polygon gas price
get_polygon_gas_price() {
    if [ -n "${POLYGON_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$POLYGON_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "50000000000"  # 50 gwei default
}

# Get Gnosis gas price
get_gnosis_gas_price() {
    if [ -n "${GNOSIS_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$GNOSIS_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "2000000000"  # 2 gwei default
}

# Get Avalanche gas price
get_avalanche_gas_price() {
    if [ -n "${AVALANCHE_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$AVALANCHE_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "30000000000"  # 30 nAVAX (nano AVAX) default
}

# Get Base gas price
get_base_gas_price() {
    if [ -n "${BASE_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$BASE_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "1000000000"  # 1 gwei default
}

# Get Arbitrum gas price
get_arbitrum_gas_price() {
    if [ -n "${ARBITRUM_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$ARBITRUM_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "100000000"  # 0.1 gwei default (Arbitrum uses lower gas prices)
}

# Get Optimism gas price
get_optimism_gas_price() {
    if [ -n "${OPTIMISM_RPC_URL:-}" ]; then
        local gas_price_wei=$(cast gas-price --rpc-url "$OPTIMISM_RPC_URL" 2>/dev/null || echo "")
        if [ -n "$gas_price_wei" ]; then
            echo "$gas_price_wei"
            return 0
        fi
    fi
    echo "1000000"  # 0.001 gwei default (Optimism uses very low gas prices)
}

# Calculate cost in native token
calculate_cost() {
    local gas_units=$1
    local gas_price_wei=$2
    local decimals=18

    # Calculate: (gas_units * gas_price_wei) / 10^18
    echo "scale=10; ($gas_units * $gas_price_wei) / 1000000000000000000" | bc
}

# Calculate USD cost (approximate)
calculate_usd_cost() {
    local native_cost=$1
    local usd_rate=$2
    echo "scale=2; $native_cost * $usd_rate" | bc
}

# Main execution
main() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}Multichain Gas Price Fetcher${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""

    # Fetch gas prices
    echo -e "${YELLOW}Fetching real-time gas prices...${NC}"

    ETH_GAS_WEI=$(get_eth_gas_price)
    CRONOS_GAS_WEI=$(get_cronos_gas_price)
    BSC_GAS_WEI=$(get_bsc_gas_price)
    POLYGON_GAS_WEI=$(get_polygon_gas_price)
    GNOSIS_GAS_WEI=$(get_gnosis_gas_price)
    AVALANCHE_GAS_WEI=$(get_avalanche_gas_price)
    BASE_GAS_WEI=$(get_base_gas_price)
    ARBITRUM_GAS_WEI=$(get_arbitrum_gas_price)
    OPTIMISM_GAS_WEI=$(get_optimism_gas_price)

    # Convert to gwei for display
    ETH_GAS_GWEI=$(wei_to_gwei "$ETH_GAS_WEI")
    CRONOS_GAS_GWEI=$(wei_to_gwei "$CRONOS_GAS_WEI")
    BSC_GAS_GWEI=$(wei_to_gwei "$BSC_GAS_WEI")
    POLYGON_GAS_GWEI=$(wei_to_gwei "$POLYGON_GAS_WEI")
    GNOSIS_GAS_GWEI=$(wei_to_gwei "$GNOSIS_GAS_WEI")
    AVALANCHE_GAS_GWEI=$(wei_to_gwei "$AVALANCHE_GAS_WEI")
    BASE_GAS_GWEI=$(wei_to_gwei "$BASE_GAS_WEI")
    ARBITRUM_GAS_GWEI=$(wei_to_gwei "$ARBITRUM_GAS_WEI")
    OPTIMISM_GAS_GWEI=$(wei_to_gwei "$OPTIMISM_GAS_WEI")

    echo -e "${GREEN}✓ Gas prices fetched${NC}"
    echo ""

    # Display gas prices
    echo -e "${BLUE}Current Gas Prices:${NC}"
    echo "  Ethereum Mainnet: ${ETH_GAS_GWEI} gwei"
    echo "  Cronos: ${CRONOS_GAS_GWEI} gwei"
    echo "  BSC: ${BSC_GAS_GWEI} gwei"
    echo "  Polygon: ${POLYGON_GAS_GWEI} gwei"
    echo "  Gnosis: ${GNOSIS_GAS_GWEI} gwei"
    echo "  Avalanche: ${AVALANCHE_GAS_GWEI} gwei"
    echo "  Base: ${BASE_GAS_GWEI} gwei"
    echo "  Arbitrum: ${ARBITRUM_GAS_GWEI} gwei"
    echo "  Optimism: ${OPTIMISM_GAS_GWEI} gwei"
    echo ""

    # Gas requirements
    MAINNET_GAS=3000000  # CCIPLogger only
    OTHER_CHAINS_GAS=8760000  # All 5 contracts with buffer

    # USD rates (approximate - update as needed)
    ETH_USD=2500
    CRO_USD=0.08
    BNB_USD=300
    MATIC_USD=0.80
    XDAI_USD=1.00
    AVAX_USD=35
    BASE_USD=2500  # Base uses ETH
    ARB_USD=2500   # Arbitrum uses ETH
    OP_USD=2500    # Optimism uses ETH

    # Calculate costs
    echo -e "${BLUE}Deployment Cost Estimates:${NC}"
    echo ""

    # Ethereum Mainnet
    ETH_COST=$(calculate_cost "$MAINNET_GAS" "$ETH_GAS_WEI")
    ETH_USD_COST=$(calculate_usd_cost "$ETH_COST" "$ETH_USD")
    echo -e "${GREEN}Ethereum Mainnet (CCIPLogger only):${NC}"
    echo "  Gas: ${MAINNET_GAS} units"
    echo "  Cost: ${ETH_COST} ETH (~\$${ETH_USD_COST})"
    echo ""

    # Cronos
    CRONOS_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$CRONOS_GAS_WEI")
    CRONOS_USD_COST=$(calculate_usd_cost "$CRONOS_COST" "$CRO_USD")
    echo -e "${GREEN}Cronos (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${CRONOS_COST} CRO (~\$${CRONOS_USD_COST})"
    echo ""

    # BSC
    BSC_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$BSC_GAS_WEI")
    BSC_USD_COST=$(calculate_usd_cost "$BSC_COST" "$BNB_USD")
    echo -e "${GREEN}BSC (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${BSC_COST} BNB (~\$${BSC_USD_COST})"
    echo ""

    # Polygon
    POLYGON_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$POLYGON_GAS_WEI")
    POLYGON_USD_COST=$(calculate_usd_cost "$POLYGON_COST" "$MATIC_USD")
    echo -e "${GREEN}Polygon (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${POLYGON_COST} MATIC (~\$${POLYGON_USD_COST})"
    echo ""

    # Gnosis
    GNOSIS_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$GNOSIS_GAS_WEI")
    GNOSIS_USD_COST=$(calculate_usd_cost "$GNOSIS_COST" "$XDAI_USD")
    echo -e "${GREEN}Gnosis (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${GNOSIS_COST} xDAI (~\$${GNOSIS_USD_COST})"
    echo ""

    # Avalanche
    AVALANCHE_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$AVALANCHE_GAS_WEI")
    AVALANCHE_USD_COST=$(calculate_usd_cost "$AVALANCHE_COST" "$AVAX_USD")
    echo -e "${GREEN}Avalanche (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${AVALANCHE_COST} AVAX (~\$${AVALANCHE_USD_COST})"
    echo ""

    # Base
    BASE_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$BASE_GAS_WEI")
    BASE_USD_COST=$(calculate_usd_cost "$BASE_COST" "$BASE_USD")
    echo -e "${GREEN}Base (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${BASE_COST} ETH (~\$${BASE_USD_COST})"
    echo ""

    # Arbitrum
    ARBITRUM_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$ARBITRUM_GAS_WEI")
    ARBITRUM_USD_COST=$(calculate_usd_cost "$ARBITRUM_COST" "$ARB_USD")
    echo -e "${GREEN}Arbitrum (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${ARBITRUM_COST} ETH (~\$${ARBITRUM_USD_COST})"
    echo ""

    # Optimism
    OPTIMISM_COST=$(calculate_cost "$OTHER_CHAINS_GAS" "$OPTIMISM_GAS_WEI")
    OPTIMISM_USD_COST=$(calculate_usd_cost "$OPTIMISM_COST" "$OP_USD")
    echo -e "${GREEN}Optimism (all 5 contracts):${NC}"
    echo "  Gas: ${OTHER_CHAINS_GAS} units"
    echo "  Cost: ${OPTIMISM_COST} ETH (~\$${OPTIMISM_USD_COST})"
    echo ""

    # Total
    TOTAL_USD=$(echo "scale=2; $ETH_USD_COST + $CRONOS_USD_COST + $BSC_USD_COST + $POLYGON_USD_COST + $GNOSIS_USD_COST + $AVALANCHE_USD_COST + $BASE_USD_COST + $ARBITRUM_USD_COST + $OPTIMISM_USD_COST" | bc)
    echo -e "${BLUE}Total Estimated Cost: ~\$${TOTAL_USD} USD${NC}"
    echo ""

    # Export for use in other scripts
    export ETH_GAS_WEI ETH_GAS_GWEI ETH_COST ETH_USD_COST
    export CRONOS_GAS_WEI CRONOS_GAS_GWEI CRONOS_COST CRONOS_USD_COST
    export BSC_GAS_WEI BSC_GAS_GWEI BSC_COST BSC_USD_COST
    export POLYGON_GAS_WEI POLYGON_GAS_GWEI POLYGON_COST POLYGON_USD_COST
    export GNOSIS_GAS_WEI GNOSIS_GAS_GWEI GNOSIS_COST GNOSIS_USD_COST
    export AVALANCHE_GAS_WEI AVALANCHE_GAS_GWEI AVALANCHE_COST AVALANCHE_USD_COST
    export BASE_GAS_WEI BASE_GAS_GWEI BASE_COST BASE_USD_COST
    export ARBITRUM_GAS_WEI ARBITRUM_GAS_GWEI ARBITRUM_COST ARBITRUM_USD_COST
    export OPTIMISM_GAS_WEI OPTIMISM_GAS_GWEI OPTIMISM_COST OPTIMISM_USD_COST
    export TOTAL_USD

    # Save to file for documentation updates
    cat > /tmp/multichain_gas_prices.json <<EOF
{
  "timestamp": "$(date -u +"%Y-%m-%d %H:%M:%S UTC")",
  "gas_prices": {
    "ethereum_mainnet": {
      "gwei": "${ETH_GAS_GWEI}",
      "wei": "${ETH_GAS_WEI}",
      "gas_units": ${MAINNET_GAS},
      "cost_eth": "${ETH_COST}",
      "cost_usd": "${ETH_USD_COST}"
    },
    "cronos": {
      "gwei": "${CRONOS_GAS_GWEI}",
      "wei": "${CRONOS_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_cro": "${CRONOS_COST}",
      "cost_usd": "${CRONOS_USD_COST}"
    },
    "bsc": {
      "gwei": "${BSC_GAS_GWEI}",
      "wei": "${BSC_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_bnb": "${BSC_COST}",
      "cost_usd": "${BSC_USD_COST}"
    },
    "polygon": {
      "gwei": "${POLYGON_GAS_GWEI}",
      "wei": "${POLYGON_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_matic": "${POLYGON_COST}",
      "cost_usd": "${POLYGON_USD_COST}"
    },
    "gnosis": {
      "gwei": "${GNOSIS_GAS_GWEI}",
      "wei": "${GNOSIS_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_xdai": "${GNOSIS_COST}",
      "cost_usd": "${GNOSIS_USD_COST}"
    },
    "avalanche": {
      "gwei": "${AVALANCHE_GAS_GWEI}",
      "wei": "${AVALANCHE_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_avax": "${AVALANCHE_COST}",
      "cost_usd": "${AVALANCHE_USD_COST}"
    },
    "base": {
      "gwei": "${BASE_GAS_GWEI}",
      "wei": "${BASE_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_eth": "${BASE_COST}",
      "cost_usd": "${BASE_USD_COST}"
    },
    "arbitrum": {
      "gwei": "${ARBITRUM_GAS_GWEI}",
      "wei": "${ARBITRUM_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_eth": "${ARBITRUM_COST}",
      "cost_usd": "${ARBITRUM_USD_COST}"
    },
    "optimism": {
      "gwei": "${OPTIMISM_GAS_GWEI}",
      "wei": "${OPTIMISM_GAS_WEI}",
      "gas_units": ${OTHER_CHAINS_GAS},
      "cost_eth": "${OPTIMISM_COST}",
      "cost_usd": "${OPTIMISM_USD_COST}"
    }
  },
  "total_usd": "${TOTAL_USD}"
}
EOF

    echo -e "${GREEN}✓ Gas prices saved to /tmp/multichain_gas_prices.json${NC}"
    echo ""
    echo -e "${YELLOW}To update documentation, run:${NC}"
    echo "  ./scripts/deployment/update-gas-estimates.sh"
}

main "$@"

