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

source ./scripts/Unix/starter.sh

# Verify Docker images
log_step "Verifying all images are present..."
if command -v jq >/dev/null 2>&1; then
  images=$(docker compose config --format json | jq -r '.services[].image // empty')
  if [ -n "$images" ]; then
    for image in $images; do
      if ! docker image inspect "$image" > /dev/null 2>&1; then
        log_error "Required images not found. Please run install.sh first."
        exit 1
      fi
      log_info "  • Found image: $image"
    done
  fi
else
  log_warning "jq is not installed; skipping image verification step."
fi

# Start services
log_step "Spinning services up..."
if ! docker compose up --no-build --detach --wait; then
  log_error "Failed to start services"
  exit 1
fi
log_success "Services are up and healthy!"

# Run pre-run tasks
log_step "Completing pre-run tasks..."

log_info "  → Running migrations..."
if ! docker compose exec app uv run manage.py migrate --no-input --verbosity 0; then
  log_error "Migrations failed"
  exit 1
fi

log_info "  → Initializing..."
if ! docker compose exec app uv run manage.py initialize; then
  log_error "Initialization failed"
  exit 1
fi

log_info "  → Setting default caches..."
if ! docker compose exec app uv run manage.py set_default_caches; then
  log_error "Cache setup failed"
  exit 1
fi

log_info "  → Rebuilding search index..."
if ! docker compose exec app uv run manage.py search_index --rebuild -f; then
  log_error "Search index rebuild failed"
  exit 1
fi

log_info "  → Collecting static files..."
if ! docker compose exec app uv run manage.py collectstatic --clear --no-input --verbosity 0; then
  log_error "Static files collection failed"
  exit 1
fi

log_success "Pre-run tasks completed successfully!"

# Cleanup
log_step "Cleaning unused Docker data..."
if ! docker system prune -f; then
  log_warning "Docker cleanup had issues, but continuing..."
fi
log_success "Unused Docker data cleaned successfully!"

echo
log_result "All done! eVibes is up and running!"
