#!/usr/bin/env bash
# Full dev cluster spinup
#
# Phase 1: Docker infra (postgres, redis, mailpit)
# Phase 2: Parallel launch via concurrently — API, UI, LLM, CAPTCHA, Tor
# Phase 3: Background health-poll until ML services report ready
#
# Usage: ./scripts/up [--no-llm] [--no-captcha] [--no-tor] [--no-ui]
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CLI_DIR="$SCRIPT_DIR/cli"
TALENT_SCOUT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
TOR_MANAGER_ROOT="$HOME/Code/@applications/@tor/services/tor-manager"

source "$CLI_DIR/core"
source "$CLI_DIR/infra"
source "$CLI_DIR/services"

# ── Flags ─────────────────────────────────────────────────────────────────────
RUN_LLM=true; RUN_CAPTCHA=true; RUN_TOR=true; RUN_UI=true
for arg in "$@"; do
  case "$arg" in
    --no-llm)     RUN_LLM=false ;;
    --no-captcha) RUN_CAPTCHA=false ;;
    --no-tor)     RUN_TOR=false ;;
    --no-ui)      RUN_UI=false ;;
    -h|--help) echo "Usage: ./scripts/up [--no-llm] [--no-captcha] [--no-tor] [--no-ui]"; exit 0 ;;
    *) err "Unknown flag: $arg"; exit 1 ;;
  esac
done

# ── Phase 1: Infrastructure ───────────────────────────────────────────────────
infra_up
echo ""

# ── Phase 3: Background readiness reporter (starts before Phase 2) ────────────
(
  sleep 5  # give processes time to register
  $RUN_LLM     && services_wait_llm     || true
  $RUN_CAPTCHA && services_wait_captcha || true
  echo ""
  ok "All services ready — http://localhost:${API_PORT}"
) &
READY_PID=$!

# ── Phase 2: Build concurrently invocation ────────────────────────────────────
log "Launching services..."

CONCURRENTLY_ARGS=(
  --prefix-colors "green,cyan,yellow,magenta,red"
  --kill-others-on-fail
)

NAMES="api"
CMDS=("bunx tsx '$TALENT_SCOUT_ROOT/src/index.ts' ui --port '$API_PORT'")

if $RUN_UI; then
  NAMES="$NAMES,ui"
  CMDS+=("bash -c 'cd \"$TALENT_SCOUT_ROOT/frontend-controlpanel\" && bun run vite --port $UI_PORT'")
fi

if $RUN_LLM; then
  NAMES="$NAMES,llm"
  CMDS+=("$CLI_DIR/services-llm")
fi

if $RUN_CAPTCHA; then
  NAMES="$NAMES,captcha"
  CMDS+=("$CLI_DIR/services-captcha")
fi

if $RUN_TOR && [ -d "$TOR_MANAGER_ROOT" ]; then
  NAMES="$NAMES,tor"
  CMDS+=("bash -c 'cd \"$TOR_MANAGER_ROOT\" && DB_HOST=localhost DB_PORT=$POSTGRES_PORT DB_USERNAME=${DB_USER:-postgres} DB_PASSWORD=${DB_PASSWORD:-postgres} DB_NAME=tor_manager REDIS_URL=redis://localhost:$REDIS_PORT/4 bunx tsx watch src/main.ts'")
fi

trap "kill $READY_PID 2>/dev/null; true" EXIT

exec bunx concurrently --names "$NAMES" "${CONCURRENTLY_ARGS[@]}" "${CMDS[@]}"
