#!/usr/bin/env bash
# uninstall.sh — 完全卸载 moziplus v2
set -euo pipefail

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

usage() {
  echo "Usage: $0 [options]"
  echo ""
  echo "Options:"
  echo "  --target=DIR    安装目录"
  echo "  --keep-data     保留 data/ 目录（移动到 data-backup-<timestamp>/）"
  echo "  --confirm       确认执行（必须传）"
  echo "  -h, --help      显示帮助"
  exit 0
}

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

if [ "$CONFIRM" = false ]; then
  echo "⚠️  This will completely uninstall moziplus v2! Use --confirm to proceed."
  echo ""
  echo "   Target: $TARGET_DIR"
  echo "   PM2:    $PM2_NAME"
  [ "$KEEP_DATA" = true ] && echo "   Data:   Will be preserved (data-backup-*/)"
  [ "$KEEP_DATA" = false ] && echo "   Data:   Will be DELETED (use --keep-data to preserve)"
  exit 1
fi

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

# ── 停止并删除 PM2 进程 ──
echo "🛑 Removing PM2 process..."
pm2 delete "$PM2_NAME" 2>/dev/null || echo "   (process not found, skipping)"
pm2 save

# ── 保留数据 ──
if [ "$KEEP_DATA" = true ] && [ -d "$TARGET_DIR/data" ]; then
  TIMESTAMP=$(date +%Y%m%d-%H%M%S)
  DATA_BACKUP="$HOME/.sanguo_projects/moziplus-v2-data-backup-$TIMESTAMP"
  echo "📦 Backing up data to: $DATA_BACKUP"
  mv "$TARGET_DIR/data" "$DATA_BACKUP"
fi

# ── 删除安装目录 ──
echo "🗑️  Removing installation: $TARGET_DIR"
rm -rf "$TARGET_DIR"

# ── 完成 ──
echo ""
echo "✅ moziplus v2 uninstalled"
[ -n "$DATA_BACKUP" ] && echo "   Data backup: $DATA_BACKUP"
echo "   Run deploy.sh to reinstall"
