#!/usr/bin/env bash
# Wait for the brain bridge, then run the Discord bot.
#
# The Discord credential is intentionally deferred: if no usable token is set
# yet, the rest of the stack (desktop, bridge, ollama) still runs fully. The bot
# just waits. Add a token to .env (DISCORD_SELFBOT_TOKEN for userbot mode, or
# DISCORD_BOT_TOKEN + DISCORD_APP_ID for the legacy normal bot) and
# `docker compose up -d` to start it.
set -e
cd /app/bot

# Two run modes, both needing DISCORD_GUILD_ID:
#   userbot : DISCORD_SELFBOT_TOKEN set (voice + Go-Live on one user account)
#   normal  : DISCORD_BOT_TOKEN + DISCORD_APP_ID set (slash commands)
# If neither is usable yet, wait instead of crash-looping so the rest of the
# stack (desktop, bridge, ollama) still runs.
USERBOT_OK=0; NORMAL_OK=0
[ -n "${DISCORD_GUILD_ID:-}" ] && [ -n "${DISCORD_SELFBOT_TOKEN:-}" ] && USERBOT_OK=1
[ -n "${DISCORD_GUILD_ID:-}" ] && [ -n "${DISCORD_BOT_TOKEN:-}" ] && [ -n "${DISCORD_APP_ID:-}" ] && NORMAL_OK=1
if [ "$USERBOT_OK" = 0 ] && [ "$NORMAL_OK" = 0 ]; then
  echo "[bot] Discord 자격증명 미설정 — 봇 대기 중."
  echo "[bot] 유저봇: DISCORD_GUILD_ID + DISCORD_SELFBOT_TOKEN, 또는"
  echo "[bot] 일반봇: DISCORD_GUILD_ID + DISCORD_BOT_TOKEN + DISCORD_APP_ID 를 .env에 넣고 're-up'."
  echo "[bot] (그동안 VNC 데스크톱 / 브릿지 / Ollama 는 정상 동작합니다.)"
  exec sleep infinity
fi

BRIDGE="${BRIDGE_URL:-http://127.0.0.1:8765}"
for i in $(seq 1 60); do
  curl -fsS "$BRIDGE/health" >/dev/null 2>&1 && break
  sleep 1
done
# Slash-command registration only applies to normal-bot mode (index.ts runs the
# normal bot whenever DISCORD_BOT_TOKEN is set; userbot mode has no slash cmds).
if [ "$NORMAL_OK" = 1 ]; then
  bun run register || echo "[bot] slash command registration failed (continuing)"
fi
exec bun run start
