#!/bin/bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
COMPOSE_FILE="$ROOT_DIR/infra/docker/docker-compose.yml"
ENV_FILE="$ROOT_DIR/.env"

if [ ! -f "$ENV_FILE" ]; then
  echo "Error: env file not found at $ENV_FILE" >&2
  exit 1
fi

if [ ! -f "$COMPOSE_FILE" ]; then
  echo "Error: compose file not found at $COMPOSE_FILE" >&2
  exit 1
fi

required_services=(init-job web worker-critical worker-default worker-bulk redis db)
available_services="$(docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" --profile job config --services)"

missing_services=()
for service in "${required_services[@]}"; do
  if ! printf '%s\n' "$available_services" | grep -qx "$service"; then
    missing_services+=("$service")
  fi
done

if [ "${#missing_services[@]}" -gt 0 ]; then
  echo "Error: runtime bootstrap gate requires services not found in compose:" >&2
  printf '  - %s\n' "${missing_services[@]}" >&2
  echo "Hint: this gate is for deployment compose that includes web/worker/init-job." >&2
  exit 1
fi

echo "=== Runtime Bootstrap Gate ==="
echo "This is the ONLY allowed entry point for deployment."
echo ""

echo "[1/2] Running bootstrap (migrate + init-data)..."
docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" --profile job run --rm init-job

echo "[2/2] Starting web and worker services..."
docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" up -d web worker-critical worker-default worker-bulk redis db

echo ""
echo "=== Bootstrap Gate Passed ==="
docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" ps
