#!/bin/bash
# Dev environment commands for @analytics
# Sourced by the top-level ./run script — do not execute directly.
# SCRIPT_DIR and ROOT_DIR are set by the caller.

ENV_FILE="$ROOT_DIR/infrastructure/.env.dev"
COMPOSE_FILE="$ROOT_DIR/infrastructure/docker-compose.dev.yaml"

_require_env() {
  if [ ! -f "$ENV_FILE" ]; then
    echo "ERROR: $ENV_FILE not found."
    echo "  cp infrastructure/.env.dev.example infrastructure/.env.dev"
    echo "  # then edit as needed"
    exit 1
  fi
}

_load_env() {
  _require_env
  set -a
  # shellcheck source=/dev/null
  source "$ENV_FILE"
  set +a
}

_start_infra() {
  docker compose -f "$COMPOSE_FILE" up -d
  echo "TimescaleDB: localhost:25434"
  echo "Redis:       localhost:26379"
  echo ""
}

case "${2:-}" in
  "")
    # ./run dev — full stack
    _load_env
    _start_infra
    echo "Starting all services..."
    (cd "$ROOT_DIR/services/collector"  && bun run dev) &
    COLLECTOR_PID=$!
    (cd "$ROOT_DIR/services/processor"  && bun run dev) &
    PROCESSOR_PID=$!
    (cd "$ROOT_DIR/services/api"        && bun run dev) &
    API_PID=$!
    (cd "$ROOT_DIR/services/realtime"   && bun run dev) &
    REALTIME_PID=$!
    echo "  Collector  → :4001"
    echo "  Processor  → (background worker)"
    echo "  API        → :4003"
    echo "  Realtime   → :4004"
    echo ""
    echo "Press Ctrl+C to stop all services."
    wait $COLLECTOR_PID $PROCESSOR_PID $API_PID $REALTIME_PID
    ;;

  infra)
    # ./run dev:infra
    _start_infra
    ;;

  collector)
    # ./run dev:collector
    _load_env
    cd "$ROOT_DIR/services/collector" && bun run dev
    ;;

  processor)
    # ./run dev:processor
    _load_env
    cd "$ROOT_DIR/services/processor" && bun run dev
    ;;

  api)
    # ./run dev:api
    _load_env
    cd "$ROOT_DIR/services/api" && bun run dev
    ;;

  realtime)
    # ./run dev:realtime
    _load_env
    cd "$ROOT_DIR/services/realtime" && bun run dev
    ;;

  stop)
    # ./run dev:stop
    docker compose -f "$COMPOSE_FILE" down
    echo "Dev infrastructure stopped."
    ;;

  status)
    # ./run dev:status
    echo "=== Infrastructure ==="
    docker compose -f "$COMPOSE_FILE" ps
    echo ""
    echo "=== Collector  (port 4001) ==="
    curl -sf http://localhost:4001/health/live && echo "" || echo "Not running"
    echo "=== API        (port 4003) ==="
    curl -sf http://localhost:4003/health/live && echo "" || echo "Not running"
    echo "=== Realtime   (port 4004) ==="
    curl -sf http://localhost:4004/health/live && echo "" || echo "Not running"
    ;;

  logs)
    # ./run dev:logs [service]
    SERVICE="${3:-}"
    if [ -n "$SERVICE" ]; then
      docker compose -f "$COMPOSE_FILE" logs -f "$SERVICE"
    else
      docker compose -f "$COMPOSE_FILE" logs -f
    fi
    ;;

  *)
    echo "Unknown dev command: dev:${2}"
    echo "Usage: ./run dev[:<infra|collector|processor|api|realtime|stop|status|logs>]"
    exit 1
    ;;
esac
