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

# Reset the project-local Supermemory Local database and restart the server in tmux.
#
# Usage:
#   OPENAI_API_KEY="sk-..." ./scripts/reset-local-supermemory.sh
#
# Or with a local OpenAI-compatible model:
#   OPENAI_BASE_URL=http://localhost:11434/v1 \
#   OPENAI_API_KEY=ollama \
#   OPENAI_MODEL=gpt-oss:20b \
#   ./scripts/reset-local-supermemory.sh

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# Load demo env if present. .env is gitignored.
if [[ -f "$ROOT_DIR/.env" ]]; then
  set -a
  # shellcheck disable=SC1091
  source "$ROOT_DIR/.env"
  set +a
fi

SESSION_NAME="${SUPERMEMORY_TMUX_SESSION:-pi-supermemory-sm}"
PORT="${SUPERMEMORY_PORT:-6767}"
LOG_FILE="${SUPERMEMORY_LOG_FILE:-/tmp/pi-supermemory-server.log}"
DATA_DIR="$ROOT_DIR/.supermemory"
URL="http://localhost:${PORT}"

has_provider_key() {
  [[ -n "${OPENAI_API_KEY:-}" ]] || \
  [[ -n "${ANTHROPIC_API_KEY:-}" ]] || \
  [[ -n "${GEMINI_API_KEY:-}" ]] || \
  [[ -n "${GROQ_API_KEY:-}" ]] || \
  ([[ -n "${WORKERS_AI_API_KEY:-}" ]] && [[ -n "${CLOUDFLARE_ACCOUNT_ID:-}" ]]) || \
  ([[ -n "${GOOGLE_VERTEX_PROJECT_ID:-}" ]] && [[ -n "${GOOGLE_VERTEX_LOCATION:-}" ]])
}

if ! command -v tmux >/dev/null 2>&1; then
  echo "tmux is required but was not found." >&2
  exit 1
fi

if ! command -v supermemory-server >/dev/null 2>&1; then
  echo "supermemory-server was not found. Run: bunx supermemory local" >&2
  exit 1
fi

if ! has_provider_key; then
  cat >&2 <<EOF
No LLM provider key/config detected in this shell.
Supermemory Local stores data locally, but still needs a model provider for extraction/summarization.

Examples:
  OPENAI_API_KEY="sk-..." ./scripts/reset-local-supermemory.sh

  OPENAI_BASE_URL=http://localhost:11434/v1 \
  OPENAI_API_KEY=ollama \
  OPENAI_MODEL=gpt-oss:20b \
  ./scripts/reset-local-supermemory.sh
EOF
  exit 1
fi

echo "Resetting Supermemory Local demo database"
echo "  repo:    $ROOT_DIR"
echo "  data:    $DATA_DIR"
echo "  tmux:    $SESSION_NAME"
echo "  url:     $URL"
echo "  log:     $LOG_FILE"

tmux has-session -t "$SESSION_NAME" 2>/dev/null && tmux kill-session -t "$SESSION_NAME" || true
rm -rf "$DATA_DIR"
rm -f "$LOG_FILE"

# Export current provider env into the tmux command without writing secrets to disk.
tmux new-session -d -s "$SESSION_NAME" \
  "cd '$ROOT_DIR' && SUPERMEMORY_PORT='$PORT' supermemory-server 2>&1 | tee '$LOG_FILE'"

echo "Starting Supermemory Local..."
for i in {1..60}; do
  if bunx supermemory local status --url "$URL" 2>/dev/null | grep -q "server:.*reachable"; then
    echo "Supermemory Local is reachable at $URL"
    echo "Run Pi with:"
    echo "  cd '$ROOT_DIR' && pi -e ."
    exit 0
  fi
  sleep 1
 done

echo "Supermemory Local did not become reachable within 60s." >&2
echo "Recent logs:" >&2
tmux capture-pane -pt "$SESSION_NAME" -S -120 2>/dev/null >&2 || tail -120 "$LOG_FILE" >&2 || true
exit 1
