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

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd -- "$SCRIPT_DIR/../.." && pwd)"
COMPOSE_FILE="$ROOT_DIR/docker/compose.local.yml"
STATE_FILE="$ROOT_DIR/.local/dev.generated.env"
WIPE=false
[ "${1:-}" = "--wipe" ] && WIPE=true

if command -v docker >/dev/null 2>&1; then RUNTIME=docker
elif command -v podman >/dev/null 2>&1; then RUNTIME=podman
else echo "Docker or Podman not found; nothing to stop." >&2; exit 0; fi

ENV_FILE="$(mktemp "${TMPDIR:-/tmp}/spoon-local.XXXXXX.env")"
trap 'rm -f "$ENV_FILE"' EXIT
sh "$ROOT_DIR/scripts/export-env" dev > "$ENV_FILE"

if [ "$WIPE" = true ]; then
  "$RUNTIME" compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" down -v
  if [ -f "$STATE_FILE" ]; then
    tmp="${STATE_FILE}.tmp"
    grep -v '^CONVEX_SELF_HOSTED_ADMIN_KEY=' "$STATE_FILE" > "$tmp" || true
    mv "$tmp" "$STATE_FILE"
  fi
  echo "Local stack and data volumes removed; generated admin key cleared."
else
  "$RUNTIME" compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" down
  echo "Local stack stopped; data volumes preserved."
fi
