#!/usr/bin/env bash
# Preflight Monad mainnet (143) CCIP stack deploy: RPC, deployer MON balance, CCIP router code.
#
# Usage: cd smom-dbis-138 && ./scripts/deployment/preflight-monad-deploy.sh

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

DEPLOYER="${DEPLOYER_ADDRESS:-0x4A666F96fC8764181194447A7dFdb7d471b301C8}"
RPC="${MONAD_MAINNET_RPC:-https://rpc.monad.xyz}"
# Infura project keys often lack Monad access — prefer public RPC unless forced.
if [[ "$RPC" =~ infura\.io/v3 ]] && [[ "${MONAD_MAINNET_RPC_FORCE_INFURA:-0}" != "1" ]]; then
  RPC="${MONAD_MAINNET_RPC_PUBLIC:-https://rpc.monad.xyz}"
fi
ROUTER="${CCIP_MONAD_ROUTER:-0x33566fE5976AAa420F3d5C64996641Fc3858CaDB}"
MIN_MON="${MONAD_DEPLOY_MIN_MON:-1}"

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

echo "=== Monad deploy preflight (chain 143) ==="
echo "Deployer: $DEPLOYER"
echo "RPC: ${RPC%%\?*}"

if ! command -v cast >/dev/null 2>&1; then
  echo -e "${RED}cast (Foundry) required${NC}" >&2
  exit 1
fi

chain_id=$(cast chain-id --rpc-url "$RPC" 2>/dev/null || echo "")
if [[ "$chain_id" != "143" ]]; then
  echo -e "${RED}RPC chain-id=$chain_id (expected 143)${NC}" >&2
  exit 1
fi
echo -e "${GREEN}RPC OK (chain 143)${NC}"

bal_wei=$(cast balance "$DEPLOYER" --rpc-url "$RPC" 2>/dev/null || echo "0")
bal_mon=$(cast --to-unit "$bal_wei" ether 2>/dev/null || echo "0")
echo "Deployer MON balance: $bal_mon"
if awk -v b="$bal_mon" -v m="$MIN_MON" 'BEGIN { exit !(b+0 >= m+0) }'; then
  echo -e "${GREEN}Balance OK (>= ${MIN_MON} MON recommended)${NC}"
else
  echo -e "${RED}Insufficient MON (need >= ${MIN_MON})${NC}" >&2
  exit 1
fi

code=$(cast code "$ROUTER" --rpc-url "$RPC" 2>/dev/null || echo "0x")
if [[ "$code" == "0x" || -z "$code" ]]; then
  echo -e "${RED}CCIP router has no code at $ROUTER${NC}" >&2
  exit 1
fi
echo -e "${GREEN}CCIP router code present${NC}"

if [[ -n "${CCIPWETH9_BRIDGE_MONAD:-}" && -n "${CCIPWETH10_BRIDGE_MONAD:-}" ]]; then
  echo -e "${YELLOW}CCIPWETH9_BRIDGE_MONAD / CCIPWETH10_BRIDGE_MONAD already set — deploy script will skip unless forced${NC}"
fi

echo ""
echo "Preflight OK. Next:"
echo "  DRY_RUN=1 ./scripts/deployment/deploy-monad-ccip-stack.sh"
echo "  ./scripts/deployment/deploy-monad-ccip-stack.sh --execute"
