#!/bin/bash
# =============================================================================
# @analytics - Run Command
# =============================================================================
#
# Usage:
#   ./run dev                     Start full dev stack (infra + all services)
#   ./run dev:infra               Start TimescaleDB + Redis only
#   ./run dev:collector           Start collector service
#   ./run dev:processor           Start processor worker
#   ./run dev:api                 Start query API
#   ./run dev:realtime            Start realtime WebSocket gateway
#   ./run dev:stop                Stop dev infrastructure
#   ./run dev:status              Health check all dev services
#   ./run dev:logs [service]      Stream dev infra logs
#
#   ./run build                   Build all packages + services (turbo)
#   ./run build:packages          Build packages only
#   ./run build:services          Build services only
#
#   ./run prod:up                 Start production stack
#   ./run prod:down               Stop production stack
#   ./run prod:restart [service]  Restart prod stack or single service
#   ./run prod:status             Health check prod services
#   ./run prod:logs [service]     Stream prod logs
#   ./run prod:keygen             Generate a new COLLECTOR_WRITE_KEY
#   ./run deploy                  Build + rsync + restart on vps-0 (1984)
#
# =============================================================================

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export ROOT_DIR

export BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
export PATH="$BUN_INSTALL/bin:$PATH"

COMMAND="${1:-dev}"
PREFIX="${COMMAND%%:*}"
export ARGV=("$@")

case "$PREFIX" in
  dev)
    # shellcheck source=scripts/run/dev.sh
    source "$ROOT_DIR/scripts/run/dev.sh" "$@"
    ;;
  build)
    # shellcheck source=scripts/run/build.sh
    source "$ROOT_DIR/scripts/run/build.sh" "$@"
    ;;
  prod)
    # shellcheck source=scripts/run/prod.sh
    source "$ROOT_DIR/scripts/run/prod.sh" "$@"
    ;;
  deploy)
    bash "$ROOT_DIR/scripts/deploy.sh"
    ;;
  *)
    echo "Unknown command: $COMMAND"
    echo ""
    echo "Usage: ./run <command>"
    echo "  dev[:<infra|collector|processor|api|realtime|stop|status|logs>]"
    echo "  build[:<packages|services>]"
    echo "  prod:<up|down|restart|status|logs|keygen>"
    echo "  deploy"
    exit 1
    ;;
esac
