#!/usr/bin/env bash
# Preflight check for Config-Ready Chains (Gnosis, Cronos, Celo, Wemix) CCIP bridge deployment.
# Verifies: RPC connectivity, deployer address, native gas balance on each chain.
# Run before deploy-bridges-config-ready-chains.sh.
#
# Usage: ./scripts/deployment/preflight-config-ready-chains.sh [gnosis|cronos|celo|wemix|all]
#        SKIP_BALANCE=1 ...  # skip balance checks (RPC-only)
#        DEPLOYER_ADDRESS=0x...  # use specific address instead of deriving from PRIVATE_KEY

set -euo pipefail

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

if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "$PROJECT_ROOT"
elif [[ -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
fi

SKIP_BALANCE="${SKIP_BALANCE:-0}"
CHAIN="${1:-all}"

# Chain config: name | chain_id | RPC_var | gas_token | min_recommended (human)
get_chain_config() {
  case "$1" in
    gnosis) echo "Gnosis|100|GNOSIS_RPC|xDAI|0.1" ;;
    cronos) echo "Cronos|25|CRONOS_RPC|CRO|1" ;;
    celo)   echo "Celo|42220|CELO_RPC|CELO|0.1" ;;
    wemix)  echo "Wemix|1111|WEMIX_RPC|WEMIX|0.4" ;;
    *)      echo "" ;;
  esac
}

# Default RPCs (from env or public)
GNOSIS_RPC="${GNOSIS_RPC:-${GNOSIS_MAINNET_RPC:-https://rpc.gnosischain.com}}"
CRONOS_RPC="${CRONOS_RPC:-${CRONOS_RPC_URL:-https://evm.cronos.org}}"
CELO_RPC="${CELO_RPC:-${CELO_MAINNET_RPC:-https://forno.celo.org}}"
WEMIX_RPC="${WEMIX_RPC:-${WEMIX_MAINNET_RPC:-https://api.wemix.com}}"

# Deployer
if [[ -n "${DEPLOYER_ADDRESS:-}" ]]; then
  DEPLOYER="${DEPLOYER_ADDRESS}"
  [[ "$DEPLOYER" != 0x* ]] && DEPLOYER="0x$DEPLOYER"
else
  if [[ -z "${PRIVATE_KEY:-}" ]]; then
    echo "Error: Set PRIVATE_KEY in .env or DEPLOYER_ADDRESS for read-only check" >&2
    exit 1
  fi
  DEPLOYER=$(cast wallet address "$PRIVATE_KEY" 2>/dev/null || true)
  if [[ -z "$DEPLOYER" ]]; then
    echo "Error: Could not derive deployer from PRIVATE_KEY (is 'cast' available?)" >&2
    exit 1
  fi
fi

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

check_chain() {
  local key="$1"
  local config
  config=$(get_chain_config "$key")
  [[ -z "$config" ]] && return 1
  local name chain_id rpc_var gas_token min_rec
  IFS='|' read -r name chain_id rpc_var gas_token min_rec <<< "$config"
  local rpc="${!rpc_var:-}"

  if [[ -z "$rpc" ]]; then
    echo -e "  ${RED}✗${NC} $name: $rpc_var not set in .env"
    return 1
  fi

  # RPC connectivity
  local res
  res=$(curl -s -m 10 -X POST "$rpc" -H "Content-Type: application/json" \
    -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null || true)
  if [[ -z "$res" ]] || ! echo "$res" | grep -q '"result"'; then
    echo -e "  ${RED}✗${NC} $name: RPC unreachable ($rpc)"
    return 1
  fi
  echo -e "  ${GREEN}✓${NC} $name: RPC OK (chain $chain_id)"

  if [[ "$SKIP_BALANCE" == "1" ]]; then
    return 0
  fi

  # Balance check
  local balance_wei
  balance_wei=$(cast balance "$DEPLOYER" --rpc-url "$rpc" 2>/dev/null || echo "0")
  local balance_eth
  balance_eth=$(echo "scale=6; $balance_wei / 1000000000000000000" | bc 2>/dev/null || echo "0")

  if [[ -z "$balance_wei" || "$balance_wei" == "0" ]]; then
    echo -e "    ${RED}✗${NC} Balance: 0 $gas_token (need $min_rec $gas_token)"
    return 1
  fi
  # Compare: balance_eth >= min_rec (use bc for decimals)
  if ! command -v bc >/dev/null 2>&1; then
    echo -e "    ${YELLOW}?${NC} Balance: $balance_eth $gas_token (bc not found, cannot compare)"
    return 0
  fi
  if [[ "$(echo "$balance_eth >= $min_rec" | bc 2>/dev/null)" != "1" ]]; then
    echo -e "    ${YELLOW}⚠${NC} Balance: $balance_eth $gas_token (recommended: $min_rec $gas_token)"
    return 1
  fi
  echo -e "    ${GREEN}✓${NC} Balance: $balance_eth $gas_token"
  return 0
}

run_checks() {
  local keys
  case "$CHAIN" in
    gnosis) keys="gnosis" ;;
    cronos) keys="cronos" ;;
    celo)   keys="celo" ;;
    wemix)  keys="wemix" ;;
    all)    keys="gnosis cronos celo wemix" ;;
    *)      echo "Usage: $0 [gnosis|cronos|celo|wemix|all]"; exit 1 ;;
  esac

  local failed=0
  for k in $keys; do
    if ! check_chain "$k"; then
      failed=1
    fi
  done
  return $failed
}

echo "=== Preflight: Config-Ready Chains (Gnosis, Cronos, Celo, Wemix) ==="
echo "Deployer: ${DEPLOYER:0:10}...${DEPLOYER: -8}"
echo "SKIP_BALANCE=$SKIP_BALANCE  CHAIN=$CHAIN"
echo ""

if run_checks; then
  echo ""
  echo "Preflight OK. Run: ./scripts/deployment/deploy-bridges-config-ready-chains.sh $CHAIN"
  exit 0
else
  echo ""
  echo "Preflight failed. Fix RPCs and gas balances before deploy."
  echo "  Gas tokens: Gnosis=xDAI, Cronos=CRO, Celo=CELO, Wemix=WEMIX"
  echo "  Recommended: Gnosis 0.1, Cronos 1, Celo 0.1, Wemix 0.4"
  exit 1
fi
