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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
COMPOSE_FILE="$ROOT_DIR/docker-compose.yml"
ENV_FILE="$ROOT_DIR/.env"
ENV_EXAMPLE="$ROOT_DIR/.env.example"
RUNTIME_DIR="$ROOT_DIR/runtime"

if ! command -v docker >/dev/null 2>&1; then
  echo "docker not found in PATH"
  exit 1
fi

if ! docker compose version >/dev/null 2>&1; then
  echo "docker compose plugin is required"
  exit 1
fi

if [[ ! -f "$ENV_FILE" && -f "$ENV_EXAMPLE" ]]; then
  cp "$ENV_EXAMPLE" "$ENV_FILE"
fi

set -a
if [[ -f "$ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  source "$ENV_FILE"
fi
set +a

PROJECT_NAME="${COMPOSE_PROJECT_NAME:-androidcast_local}"

echo "Stopping and removing orchestration stack..."
docker compose -f "$COMPOSE_FILE" down --remove-orphans --volumes --rmi local || true

echo "Removing leftover containers with compose project label..."
docker ps -aq --filter "label=com.docker.compose.project=${PROJECT_NAME}" | while read -r cid; do
  [[ -n "$cid" ]] && docker rm -f "$cid" || true
done

echo "Removing leftover compose networks..."
docker network ls -q --filter "label=com.docker.compose.project=${PROJECT_NAME}" | while read -r nid; do
  [[ -n "$nid" ]] && docker network rm "$nid" || true
done

echo "Removing leftover compose volumes..."
docker volume ls -q --filter "label=com.docker.compose.project=${PROJECT_NAME}" | while read -r vid; do
  [[ -n "$vid" ]] && docker volume rm "$vid" || true
done

echo "Removing orchestration screen sessions if present..."
if command -v screen >/dev/null 2>&1; then
  screen_output="$(screen -ls 2>/dev/null || true)"
  printf '%s\n' "$screen_output" | awk '/androidcast|orchestration/ {print $1}' | while read -r session; do
    [[ -n "$session" ]] && screen -S "$session" -X quit || true
  done
fi

echo "Cleaning generated runtime artifacts..."
rm -f "$RUNTIME_DIR/crash-config.php"
rm -f "$RUNTIME_DIR/db-init/010_schema.sql" \
      "$RUNTIME_DIR/db-init/040_ticket_workflow.sql" \
      "$RUNTIME_DIR/db-init/050_ticket_attachments.sql"
mkdir -p "$RUNTIME_DIR/db-init"
touch "$RUNTIME_DIR/db-init/.gitkeep"

echo "Orchestration cleanup complete."
