#!/usr/bin/env bash
# reset-data.sh — 清空 moziplus v2 运行数据（保留配置）
set -euo pipefail

TARGET_DIR="${MOZIPLUS_V2_DIR:-$HOME/.sanguo_projects/sanguo_moziplus_v2}"
PM2_NAME="sanguo-moziplus-v2"
CONFIRM=false
PROJECT_FILTER=""

usage() {
  echo "Usage: $0 [options]"
  echo ""
  echo "Options:"
  echo "  --target=DIR       安装目标目录"
  echo "  --project=NAME     只清指定项目数据（可多次使用，逗号分隔）"
  echo "  --confirm          确认执行（必须传）"
  echo "  -h, --help         显示帮助"
  echo ""
  echo "Examples:"
  echo "  $0 --confirm                       # 清空所有数据"
  echo "  $0 --project=demo --confirm        # 只清 demo 项目"
  echo "  $0 --project=demo,test --confirm   # 清 demo 和 test 项目"
  exit 0
}

for arg in "$@"; do
  case "$arg" in
    --target=*) TARGET_DIR="${arg#*=}" ;;
    --project=*) PROJECT_FILTER="${arg#*=}" ;;
    --confirm) CONFIRM=true ;;
    -h|--help) usage ;;
  esac
done

if [ "$CONFIRM" = false ]; then
  echo "⚠️  This will delete running data! Use --confirm to proceed."
  echo ""
  if [ -n "$PROJECT_FILTER" ]; then
    echo "   Would delete data for project(s): $PROJECT_FILTER"
  else
    echo "   Would delete ALL project data (keeping config/)"
  fi
  exit 1
fi

DATA_DIR="$TARGET_DIR/data"

if [ ! -d "$DATA_DIR" ]; then
  echo "❌ Data directory not found: $DATA_DIR" && exit 1
fi

# ── 停服务 ──
echo "🛑 Stopping $PM2_NAME..."
pm2 stop "$PM2_NAME" 2>/dev/null || true

# 确保 trap 恢复服务
cleanup() {
  echo ""
  echo "▶️  Ensuring $PM2_NAME is running..."
  pm2 restart "$PM2_NAME" 2>/dev/null || pm2 start "$PM2_NAME" 2>/dev/null || true
}
trap cleanup EXIT

# ── 清数据 ──
echo ""
if [ -n "$PROJECT_FILTER" ]; then
  # 指定项目
  IFS=',' read -ra PROJECTS <<< "$PROJECT_FILTER"
  for proj in "${PROJECTS[@]}"; do
    proj=$(echo "$proj" | xargs)  # trim
    PROJ_DIR="$DATA_DIR/$proj"
    if [ -d "$PROJ_DIR" ]; then
      echo "🗑️  Deleting $proj data..."
      rm -rf "$PROJ_DIR"
    else
      echo "⚠️  Project dir not found: $PROJ_DIR (skipped)"
    fi
  done
else
  # 清空所有项目数据
  echo "🗑️  Deleting all project data..."
  find "$DATA_DIR" -mindepth 1 -maxdepth 1 -type d ! -name '_registry*' -exec rm -rf {} +
  # 清 registry.db（会自动重建）
  rm -f "$DATA_DIR/registry.db" "$DATA_DIR/registry.db-shm" "$DATA_DIR/registry.db-wal"
fi

# ── 清 inbox 和 logs ──
echo "🗑️  Cleaning inbox and logs..."
rm -f "$TARGET_DIR/inbox/"*.jsonl 2>/dev/null || true
rm -f "$TARGET_DIR/logs/"* 2>/dev/null || true

# ── 重启服务 ──（trap EXIT 也会执行，但这里显式做一次）
echo ""
echo "▶️  Starting $PM2_NAME..."
pm2 start "$PM2_NAME"
trap - EXIT  # 清除 trap，避免重复执行

# ── 完成 ──
echo ""
if [ -n "$PROJECT_FILTER" ]; then
  echo "✅ Project data reset: $PROJECT_FILTER"
else
  echo "✅ All data reset (config preserved)"
fi
echo "   URL: http://localhost:8083/"
