#!/usr/bin/env bash
set -euo pipefail

if [[ "${CI:-}" == "true" ]]; then
  # ── CI path ────────────────────────────────────────────────────────
  echo "[txnbot-ci] Starting Transaction Bot..."

  : "${TXNBOT_PRIVATE_KEY:?TXNBOT_PRIVATE_KEY is required}"
  : "${RPC_URL:?RPC_URL is required}"
  : "${KRAIKEN_ADDRESS:?KRAIKEN_ADDRESS is required}"
  : "${STAKE_ADDRESS:?STAKE_ADDRESS is required}"
  : "${LIQUIDITY_MANAGER_ADDRESS:?LIQUIDITY_MANAGER_ADDRESS is required}"

  cat > /tmp/txnBot.env <<EOF
TXNBOT_PRIVATE_KEY=${TXNBOT_PRIVATE_KEY}
RPC_URL=${RPC_URL}
KRAIKEN_ADDRESS=${KRAIKEN_ADDRESS}
STAKE_ADDRESS=${STAKE_ADDRESS}
LIQUIDITY_MANAGER_ADDRESS=${LIQUIDITY_MANAGER_ADDRESS}
POOL_ADDRESS=${POOL_ADDRESS:-}
WETH_ADDRESS=${WETH_ADDRESS:-0x4200000000000000000000000000000000000006}
EOF

  export TXN_BOT_ENV_FILE=/tmp/txnBot.env

  echo "[txnbot-ci] Environment configured:"
  echo "  RPC_URL: ${RPC_URL}"
  echo "  KRAIKEN_ADDRESS: ${KRAIKEN_ADDRESS}"

  echo "[txnbot-ci] Building TypeScript..."
  npm run build

  exec npm run start
fi

# ── Local dev path ─────────────────────────────────────────────────
ROOT_DIR=/workspace

# shellcheck source=entrypoint-common.sh
source "$ROOT_DIR/containers/entrypoint-common.sh"

entrypoint_checkout_branch "$ROOT_DIR" "txnbot-entrypoint"

TXNBOT_ENV_FILE=$ROOT_DIR/tmp/containers/txnBot.env
BOT_DIR=$ROOT_DIR/services/txnBot

while [[ ! -f "$TXNBOT_ENV_FILE" ]]; do
  echo "[txnbot-entrypoint] waiting for env file"
  sleep 2
done

entrypoint_require_kraiken_lib "$ROOT_DIR" "txnbot-entrypoint"

cd "$BOT_DIR"

entrypoint_install_deps "txnbot-entrypoint"

echo "[txnbot-entrypoint] Building TypeScript..."
npm run build

export TXN_BOT_ENV_FILE="$TXNBOT_ENV_FILE"
exec npm run start
