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

if [ ! -d "./evibes" ]; then
  printf "\e[31m❌  Please run this script from the project's root (where the 'evibes' directory lives).\e[0m\n"
  exit 1
fi

PURPLE="\e[38;2;121;101;209m"
RESET="\e[0m"
GRAY="\e[90m"

SOURCE="${BASH_SOURCE[0]:-$0}"
SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" && pwd)"
ART_PATH="$SCRIPT_DIR/../ASCII_ART_EVIBES"

if [ ! -f "$ART_PATH" ]; then
  printf "\e[31m❌  Could not find ASCII art at %s\e[0m\n" "$ART_PATH"
  exit 1
fi

while IFS= read -r line; do
  printf "%b%s%b\n" "$PURPLE" "$line" "$RESET"
done < "$ART_PATH"

printf "\n%b                                                                       by WISELESS TEAM%b\n\n" "$GRAY" "$RESET"

printf "\e[32mVerifying all images are present…\e[0m\n"

if ! command -v jq >/dev/null 2>&1; then
  printf "\e[31mjq is required for verifying images. Please install jq.\e[0m\n"
  exit 1
fi

images=$(docker compose config --format json | jq -r '.services[]?.image // empty')

for image in $images; do
  if ! docker image inspect "$image" >/dev/null 2>&1; then
    printf "\e[31mRequired images not found. Please run install.sh first.\e[0m\n"
    exit 1
  fi
  printf "  • Found image: %s\n" "$image"
done

printf "\e[36mStarting services…\e[0m\n"
docker compose up --no-build --detach --wait

printf "\e[36mApplying migrations…\e[0m\n"
docker compose exec app poetry run python manage.py migrate --no-input

printf "\e[36mCollecting static files…\e[0m\n"
docker compose exec app poetry run python manage.py collectstatic --no-input

printf "\e[36mSetting default caches…\e[0m\n"
docker compose exec app poetry run python manage.py set_default_caches

printf "\e[36mCleaning up…\e[0m\n"
docker compose exec app poetry run python manage.py set_default_caches

printf "\e[32mAll done! eVibes is up and running.\e[0m\n"
