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

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

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)
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

# Clear multi-workspace directories and recreate default
if [ -d workspaces ]; then
  echo "  Clearing workspaces/..."
  rm -rf workspaces
fi
mkdir -p workspaces/default

# 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 ./setup.sh to reconfigure, or npm install && npm start"
fi

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