#!/usr/bin/env bash

set -e

# Deploy CCIP Router Contract
# This script deploys the CCIP Router contract to the network

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

# Configuration
RPC_URL="${RPC_URL:-}"
PRIVATE_KEY="${PRIVATE_KEY:-}"
FEE_TOKEN="${FEE_TOKEN:-}" # LINK token address
BASE_FEE="${BASE_FEE:-1000000000000000000}" # 1 LINK in wei
DATA_FEE_PER_BYTE="${DATA_FEE_PER_BYTE:-1000000000000000}" # 0.001 LINK per byte

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

RPC_URL="${RPC_URL:-${RPC_URL_138:-${CHAIN138_RPC_URL:-http://localhost:8545}}}"
if ! require_private_key_env; then
    exit 1
fi

if [ -z "$FEE_TOKEN" ]; then
    echo "ERROR: FEE_TOKEN not available. Set it in smom-dbis-138/.env or repo .env." >&2
    exit 1
fi

echo "Deploying CCIP Router..."
echo "RPC URL: $RPC_URL"
echo "Fee Token: $FEE_TOKEN"
echo "Base Fee: $BASE_FEE"
echo "Data Fee Per Byte: $DATA_FEE_PER_BYTE"

forge script script/DeployCCIPRouter.s.sol \
    --rpc-url "$RPC_URL" \
    --broadcast \
    --private-key "$PRIVATE_KEY" \
    --sig "run(address,uint256,uint256)" \
    "$FEE_TOKEN" \
    "$BASE_FEE" \
    "$DATA_FEE_PER_BYTE"

echo "CCIP Router deployment complete!"
