#!/usr/bin/env bash
# safe_rm: interactive, archive-only replacement for rm
set -euo pipefail

TRASH_BASE="${TRASH_BASE:-$HOME/.trash}"
TRASH_ARCHIVE_BASE="${TRASH_ARCHIVE_BASE:-$HOME/.trash_archive}"
TS="$(date +%Y%m%d_%H%M%S)"
mkdir -p "$TRASH_BASE" "$TRASH_ARCHIVE_BASE"

full_cmd="rm $*"
paths=()
danger=false

for arg in "$@"; do
  case "$arg" in
    -r|-R|-f|-rf|-fr)
      danger=true
      ;;
    --)
      shift
      for rest in "$@"; do paths+=("$rest"); done
      break
      ;;
    -*)
      ;;
    *)
      paths+=("$arg")
      ;;
  esac
done

if [ "${#paths[@]}" -eq 0 ]; then
  echo "safe_rm: no paths given" >&2
  exit 1
fi

canonicalize() {
  python3 - "$1" <<'PY2'
import os, sys
print(os.path.realpath(sys.argv[1]))
PY2
}

trash_real="$(canonicalize "$TRASH_BASE")"
archive_real="$(canonicalize "$TRASH_ARCHIVE_BASE")"

echo "=========================================="
echo "  ⚠️  危险操作检测"
echo "=========================================="
echo

echo "命令: $full_cmd"
if [ "$danger" = true ]; then
  echo "风险: 使用 -rf 强制删除 ${#paths[@]} 个文件/目录"
else
  echo "风险: 删除 ${#paths[@]} 个文件/目录"
fi
echo

echo "⚠️  警告：此操作可能删除多个文件"
echo
echo "要删除的文件/目录（共 ${#paths[@]} 个）:"
for target in "${paths[@]}"; do
  echo "  - $target"
done
echo

read -r -p "请输入 yes 以继续，或按 Ctrl+C 取消： " answer
if [ "$answer" != "yes" ]; then
  echo "safe_rm: 已取消" >&2
  exit 1
fi

for target in "${paths[@]}"; do
  if [ ! -e "$target" ]; then
    echo "safe_rm: not found: $target" >&2
    continue
  fi

  target_real="$(canonicalize "$target")"
  base_name="$(basename -- "$target")"
  dest_root="$TRASH_BASE"

  case "$target_real" in
    "$trash_real"|"$trash_real"/*)
      dest_root="$TRASH_ARCHIVE_BASE"
      ;;
    "$archive_real"|"$archive_real"/*)
      dest_root="${TRASH_ARCHIVE_BASE}_overflow"
      mkdir -p "$dest_root"
      ;;
  esac

  dest="${dest_root}/${base_name}_$TS"
  if [ -e "$dest" ]; then
    dest="${dest}_$$"
  fi

  mv -- "$target" "$dest"
  echo "safe_rm: moved $target -> $dest" >&2
done
