#!/usr/bin/env bash
# Deploy to chains with sufficient native token balance (Avalanche, Arbitrum, Cronos).
# Run check-balances-gas-and-deploy.sh first to confirm balances.
# Chain 138 phased core is deployed separately (check-balances-gas-and-deploy.sh --deploy).
#
# Requires: PRIVATE_KEY, CCIP_*_ROUTER, CCIP_*_LINK_TOKEN, *_SELECTOR, *_RPC_URL per chain.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
cd "$PROJECT_ROOT"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
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:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi

# Load .env
if [ -f .env ]; then
  set -a
  source .env
  set +a
fi

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

if [ -z "${PRIVATE_KEY:-}" ]; then
  echo -e "${RED}ERROR: PRIVATE_KEY not set in .env${NC}"
  exit 1
fi

# Chains with sufficient balance (from last balance check): Avalanche, Arbitrum, Cronos
# Prefer INFURA_PROJECT_ID (+ optional INFURA_PROJECT_SECRET) when set; else public RPCs
[[ -f "$SCRIPT_DIR/../lib/infura.sh" ]] && source "$SCRIPT_DIR/../lib/infura.sh"
_av_rpc=$(build_infura_rpc "avalanche-mainnet" 2>/dev/null || true)
_ar_rpc=$(build_infura_rpc "arbitrum-mainnet" 2>/dev/null || true)
AVALANCHE_RPC="${AVALANCHE_RPC_URL:-${AVALANCHE_RPC:-${_av_rpc:-https://avalanche-c-chain.publicnode.com}}}"
ARBITRUM_RPC="${ARBITRUM_MAINNET_RPC:-${ARBITRUM_RPC:-${_ar_rpc:-https://arbitrum-one.publicnode.com}}}"
CRONOS_RPC="${CRONOS_RPC_URL:-${CRONOS_RPC:-https://evm.cronos.org}}"

deploy_chain() {
  local name="$1"
  local rpc="$2"
  local chain_id="$3"
  echo -e "${YELLOW}Deploying to ${name} (chain ${chain_id})...${NC}"
  forge script script/DeployAll.s.sol:DeployAll \
    --rpc-url "$rpc" \
    --chain-id "$chain_id" \
    --private-key "$PRIVATE_KEY" \
    --broadcast \
    --slow \
    -vvvv || {
    echo -e "${RED}✗ ${name} deployment failed${NC}"
    return 1
  }
  echo -e "${GREEN}✓ ${name} deployment complete${NC}"
  echo ""
}

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Deploy to chains with sufficient balance${NC}"
echo -e "${BLUE}========================================${NC}"
echo "Chains: Avalanche, Arbitrum, Cronos"
echo ""

# Verify required CCIP env vars
for chain in AVALANCHE ARBITRUM CRONOS; do
  router="CCIP_${chain}_ROUTER"
  link="CCIP_${chain}_LINK_TOKEN"
  selector="${chain}_SELECTOR"
  if [ -z "${!router:-}" ] || [ -z "${!link:-}" ] || [ -z "${!selector:-}" ]; then
    echo -e "${RED}ERROR: Missing ${router}, ${link}, or ${selector} in .env${NC}"
    exit 1
  fi
done

# Deploy (skip --verify to avoid needing chain-specific explorer API keys)
deploy_chain "Avalanche" "$AVALANCHE_RPC" "43114"
deploy_chain "Arbitrum"  "$ARBITRUM_RPC"  "42161"
deploy_chain "Cronos"    "$CRONOS_RPC"    "25"

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Deployments complete${NC}"
echo -e "${GREEN}========================================${NC}"
echo "Next: update .env with deployed addresses; run verify manually if needed."
