#!/usr/bin/env bash
# Infura RPC URL builder: uses INFURA_PROJECT_ID and optional INFURA_PROJECT_SECRET (Basic Auth).
# Usage: source "$SCRIPT_DIR/lib/infura.sh"  # then call build_infura_rpc "avalanche-mainnet"
# When INFURA_PROJECT_SECRET is set, the URL uses Basic Auth (required for some operations e.g. eth_sendTransaction).
# Set INFURA_PROJECT_ID and optionally INFURA_PROJECT_SECRET in .env; never commit secrets.

build_infura_rpc() {
  local host_path="${1:?Usage: build_infura_rpc <host-path> e.g. avalanche-mainnet}"
  local id="${INFURA_PROJECT_ID:-}"
  local secret="${INFURA_PROJECT_SECRET:-}"
  if [[ -z "$id" ]]; then
    return 1
  fi
  local auth=""
  if [[ -n "$secret" && ! "$secret" =~ \$\{ ]]; then
    local encoded
    encoded=$(printf '%s' "$secret" | python3 -c "import sys, urllib.parse; print(urllib.parse.quote(sys.stdin.read(), safe=''))" 2>/dev/null) || encoded="$secret"
    auth="${id}:${encoded}@"
  fi
  echo "https://${auth}${host_path}.infura.io/v3/${id}"
}

# Given any RPC URL, if it is an Infura URL (https://HOST.infura.io/v3/PROJECT_ID) and
# INFURA_PROJECT_SECRET is set, return the same URL with Basic Auth so requests succeed.
# If the URL already contains @ (already has auth), or is not Infura, return as-is.
# Use this before passing .env RPC vars to cast/curl so Infura is accessed with the secret.
ensure_infura_rpc_url() {
  local url="${1:-}"
  [[ -z "$url" ]] && echo "" && return 0
  [[ "$url" == *"@"* ]] && echo "$url" && return 0
  if [[ "$url" =~ ^https://([a-zA-Z0-9.-]+)\.infura\.io/v3/([a-zA-Z0-9]+)$ ]]; then
    local host="${BASH_REMATCH[1]}"
    local id="${BASH_REMATCH[2]}"
    local secret="${INFURA_PROJECT_SECRET:-}"
    if [[ -n "$secret" && ! "$secret" =~ \$\{ ]]; then
      local encoded
      encoded=$(printf '%s' "$secret" | python3 -c "import sys, urllib.parse; print(urllib.parse.quote(sys.stdin.read(), safe=''))" 2>/dev/null) || encoded="$secret"
      echo "https://${id}:${encoded}@${host}.infura.io/v3/${id}"
      return 0
    fi
  fi
  echo "$url"
}

# Build Infura Gas API URL for Ethereum mainnet (networks/1).
# INFURA_GAS_API can be set to full URL; otherwise uses INFURA_PROJECT_ID.
get_infura_gas_api_url() {
  local url="${INFURA_GAS_API:-}"
  if [[ -n "$url" ]]; then
    if [[ "$url" == *"/v3/"* ]]; then
      local key="${url#*v3/}"
      key="${key%%/*}"
      echo "https://gas.api.infura.io/v3/${key}/networks/1/suggestedGasFees"
      return
    fi
    echo "$url"
    return
  fi
  local id="${INFURA_PROJECT_ID:-}"
  if [[ -n "$id" ]]; then
    echo "https://gas.api.infura.io/v3/${id}/networks/1/suggestedGasFees"
  fi
}
