#!/bin/bash
# Reset agent to a clean state
# Usage: ./reset.sh [--hard]
#
# Default: Clears runtime state (db, journal, wake-state, evolution) but PRESERVES workspace files
# --hard:  Also removes workspaces/, site/, config.json, node_modules/ (full reset)

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# Fix Windows line endings if present
if cat -v "$0" | head -1 | grep -q '\^M'; then
  tr -d '\r' < "$0" > "$0.tmp" && mv "$0.tmp" "$0" && chmod +x "$0"
  exec bash "$0" "$@"
fi

HARD=false
if [ "$1" = "--hard" ]; then
  HARD=true
fi

echo ""
echo "Resetting agent..."
echo ""

# Stop the agent if running
AGENT_PID=$(pgrep -f "node.*agent.mjs" 2>/dev/null | head -1 || true)
if [ -n "$AGENT_PID" ]; then
  echo "  Stopping agent (PID: $AGENT_PID)..."
  kill "$AGENT_PID" 2>/dev/null || true
  sleep 1
fi

# Remove database (all tables: events, memories, skills, api_usage, tasks,
# kg_entities, kg_relations, workspaces, ingestion_queue, cognitive_log,
# sessions, background_tasks)
if ls agent.db* 1>/dev/null 2>&1; then
  echo "  Removing database..."
  rm -f agent.db agent.db-shm agent.db-wal
fi

# Clear journal
if [ -f journal.md ]; then
  echo "  Clearing journal..."
  echo "# Journal" > journal.md
fi

# Reset wake state
rm -f wake-state.md
echo "  Cleared wake state"

# Reset evolution state
rm -f evolution.yaml
echo "  Cleared evolution state"

# Clear heartbeat
rm -f .heartbeat

# Clear legacy workspace/ (preserve .claude/ metadata)
if [ -d workspace ]; then
  echo "  Clearing legacy workspace/..."
  find workspace -mindepth 1 -not -path 'workspace/.claude*' -delete 2>/dev/null || true
fi

# Workspace files are preserved by default — only deleted with --hard
if [ "$HARD" = false ]; then
  echo "  Workspace files preserved (use --hard to remove)"
else
  # Clear multi-workspace directories and recreate default
  if [ -d workspaces ]; then
    echo "  Clearing workspaces/..."
    rm -rf workspaces
  fi
  mkdir -p workspaces/default
fi

# Clear data/ (wake word recordings, etc) — preserve .gitkeep and ONNX models
if [ -d data/wake-words ]; then
  echo "  Clearing wake word recordings..."
  find data/wake-words -type f -not -name '.gitkeep' -delete 2>/dev/null || true
fi

# Clear generated site
if [ -d site ]; then
  echo "  Removing generated site..."
  rm -rf site
fi

# Clear logs
rm -f agent.log watchdog.log

# Clear uploads (ingestion temp files)
if [ -d uploads ]; then
  echo "  Clearing uploads/..."
  rm -rf uploads
fi

if [ "$HARD" = true ]; then
  echo ""
  echo "  Hard reset — removing config and dependencies..."
  rm -f config.json
  rm -rf node_modules
  echo "  Run 'bash setup.sh' to reconfigure, or npm install && npm start"
fi

echo ""
echo "Reset complete. Run 'npm start' to start fresh."
echo ""
