#!/bin/bash
# ─────────────────────────────────────────────────────────────────────────────
# Spacebot (Sofiia Telegram agent) start script
# Usage: ./ops/scripts/start_spacebot.sh [stop|restart|status|logs]
# ─────────────────────────────────────────────────────────────────────────────
set -e

REPO_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
SPACEBOT_BIN="/Users/apple/github-projects/spacebot/target/release/spacebot"
SPACEBOT_DIR="/Users/apple/.spacebot"
ENV_FILE="${REPO_DIR}/.env"
PID_FILE="${SPACEBOT_DIR}/spacebot.pid"
LOG_FILE="${SPACEBOT_DIR}/logs/spacebot.log.$(date +%Y-%m-%d)"
export PATH="$HOME/.bun/bin:$PATH"

load_env() {
  if [ -f "$ENV_FILE" ]; then
    set -a; source "$ENV_FILE"; set +a
  fi
  export ZHIPU_API_KEY="${GLM5_API_KEY}"
}

is_running() {
  [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null
}

cmd="${1:-start}"

case "$cmd" in
  start)
    if is_running; then
      echo "Spacebot already running (PID: $(cat $PID_FILE))"
      exit 0
    fi
    load_env
    echo "Starting Spacebot..."
    nohup $SPACEBOT_BIN --config "${SPACEBOT_DIR}/config.toml" > /tmp/spacebot.out 2>&1 &
    sleep 3
    if is_running; then
      echo "✓ Spacebot started (PID: $(cat $PID_FILE))"
      echo "  Bot: @SofiiaDaarionbot"
      echo "  Logs: $LOG_FILE"
    else
      echo "✗ Spacebot failed to start. Check logs: $LOG_FILE"
      exit 1
    fi
    ;;
  stop)
    if is_running; then
      kill "$(cat "$PID_FILE")"
      echo "✓ Spacebot stopped"
    else
      echo "Spacebot not running"
    fi
    ;;
  restart)
    $0 stop 2>/dev/null; sleep 2; $0 start
    ;;
  status)
    if is_running; then
      echo "✓ Spacebot running (PID: $(cat $PID_FILE))"
      tail -3 "$LOG_FILE" 2>/dev/null
    else
      echo "✗ Spacebot not running"
    fi
    ;;
  logs)
    tail -f "$LOG_FILE"
    ;;
  *)
    echo "Usage: $0 {start|stop|restart|status|logs}"
    exit 1
    ;;
esac
