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

# Local dev entrypoint (all-in-one container: Node + Python).
# Usage:
#   ./dev.sh            # up --build (foreground)
#   ./dev.sh up         # same as above
#   ./dev.sh up -d      # detached
#   ./dev.sh logs       # follow logs
#   ./dev.sh down       # stop and remove
#   ./dev.sh rebuild    # rebuild image

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

CMD="${1:-up}"
shift || true

case "$CMD" in
  up)
    # Start in background, then wait for Node self-check + health endpoint.
    docker compose up -d --build "$@"
    echo "[dev] waiting for server health..."
    deadline=$((SECONDS + 90))
    ok=0
    while [ $SECONDS -lt $deadline ]; do
      if curl -fsS "http://127.0.0.1:3000/api/health" >/dev/null 2>&1; then
        ok=1
        break
      fi
      # If container exited, fail fast.
      if ! docker compose ps --status running | grep -q "aivideo"; then
        break
      fi
      sleep 1
    done
    if [ "$ok" -ne 1 ]; then
      echo "[dev] server failed to become healthy (self-check likely failed)." >&2
      docker compose logs --tail=200 aivideo || true
      exit 1
    fi
    echo "[dev] server ready: http://127.0.0.1:3000"
    docker compose logs -f --tail=50 aivideo
    ;;
  rebuild)
    docker compose build "$@"
    ;;
  logs)
    docker compose logs -f --tail=200 "$@"
    ;;
  down)
    docker compose down "$@"
    ;;
  *)
    echo "Unknown command: $CMD" >&2
    echo "Usage: ./dev.sh [up|rebuild|logs|down] [args...]" >&2
    exit 2
    ;;
esac

