#!/usr/bin/env bash
set -euo pipefail

# Dev mode: run services with bind-mounted source code + auto-reload
# Usage:
#   ./dev.sh                  # Start all services
#   ./dev.sh blog market      # Start specific services (+ infra)
#   ./dev.sh --build blog     # Rebuild image first, then start
#   ./dev.sh down             # Stop everything
#   ./dev.sh logs blog        # Tail logs for a service

COMPOSE="docker compose -p rose-ash-dev -f docker-compose.yml -f docker-compose.dev.yml"
INFRA_SERVICES="db pgbouncer redis redis-auth"

case "${1:-up}" in
  down)
    $COMPOSE down
    ;;
  logs)
    shift
    $COMPOSE logs -f "$@"
    ;;
  test-run)
    # One-shot: all unit tests (headless, no dashboard)
    $COMPOSE run --rm test-unit python -m pytest \
      shared/ artdag/core/tests/ artdag/core/artdag/sexp/ \
      artdag/l1/tests/ artdag/l1/sexp_effects/ \
      -v --tb=short \
      --ignore=artdag/l1/tests/test_jax_primitives.py \
      --ignore=artdag/l1/tests/test_jax_pipeline_integration.py \
      -k "not gpu and not cuda"
    ;;
  test-integration)
    # One-shot: integration tests (needs ffmpeg, heavier)
    $COMPOSE run --rm test-integration
    ;;
  watch)
    # Auto-rerun unit tests on file changes (stays running)
    $COMPOSE up test-unit
    ;;
  build)
    shift
    if [[ $# -eq 0 ]]; then
      $COMPOSE build
    else
      $COMPOSE build "$@"
    fi
    ;;
  *)
    # Collect flags and service names
    BUILD_FLAG=""
    SERVICES=()
    for arg in "$@"; do
      if [[ "$arg" == "--build" ]]; then
        BUILD_FLAG="--build"
      else
        SERVICES+=("$arg")
      fi
    done

    if [[ ${#SERVICES[@]} -eq 0 ]]; then
      # Start everything
      $COMPOSE up $BUILD_FLAG
    else
      # Start infra + requested app services
      $COMPOSE up $BUILD_FLAG $INFRA_SERVICES "${SERVICES[@]}"
    fi
    ;;
esac
