#!/usr/bin/env bash
set -Eeuo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
DRY_RUN=0

usage() {
  cat <<'EOF'
用法:
  bash scripts/prune-package.sh [--dry-run]

说明:
  删除项目里的 Git 元数据、本地依赖、浏览器缓存和构建产物，
  保留源码、部署脚本、锁文件和环境变量模板。

参数:
  --dry-run   只打印将删除的内容，不实际删除
  -h, --help  显示帮助
EOF
}

log() {
  printf '[prune-package] %s\n' "$*"
}

remove_entry() {
  local absolute_path="$1"
  local relative_path="${absolute_path#"$ROOT_DIR"/}"

  if [[ ! -e "$absolute_path" && ! -L "$absolute_path" ]]; then
    return
  fi

  if [[ "$absolute_path" == "$ROOT_DIR" ]]; then
    return
  fi

  if [[ "$DRY_RUN" -eq 1 ]]; then
    log "would remove ${relative_path}"
    return
  fi

  rm -rf "$absolute_path"
  log "removed ${relative_path}"
}

remove_fixed_paths() {
  local relative_path
  local fixed_paths=(
    ".git"
    "node_modules"
    "chatbot/node_modules"
    "dist"
    "chatbot/output"
    "automation/.browser"
    "chatbot/.browser"
    "logs"
    "supabase/.temp"
    ".cache"
    ".turbo"
    "coverage"
    "playwright-report"
    "test-results"
  )

  for relative_path in "${fixed_paths[@]}"; do
    remove_entry "$ROOT_DIR/$relative_path"
  done
}

remove_named_directories() {
  local directory_name="$1"

  while IFS= read -r -d '' matched_path; do
    remove_entry "$matched_path"
  done < <(
    find "$ROOT_DIR" \
      \( -path "$ROOT_DIR/.git" -o -path "$ROOT_DIR/node_modules" -o -path "$ROOT_DIR/chatbot/node_modules" \) -prune -o \
      -type d -name "$directory_name" -print0
  )
}

remove_named_files() {
  local file_name="$1"

  while IFS= read -r -d '' matched_path; do
    remove_entry "$matched_path"
  done < <(
    find "$ROOT_DIR" \
      \( -path "$ROOT_DIR/.git" -o -path "$ROOT_DIR/node_modules" -o -path "$ROOT_DIR/chatbot/node_modules" \) -prune -o \
      -type f -name "$file_name" -print0
  )
}

main() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --dry-run)
        DRY_RUN=1
        ;;
      -h|--help)
        usage
        exit 0
        ;;
      *)
        printf '[prune-package] ERROR: 未知参数: %s\n' "$1" >&2
        exit 1
        ;;
    esac
    shift
  done

  log "start pruning package contents"

  remove_fixed_paths
  remove_named_directories ".browser"
  remove_named_directories ".vite"
  remove_named_directories "coverage"
  remove_named_directories "playwright-report"
  remove_named_directories "test-results"
  remove_named_files ".DS_Store"
  remove_named_files "*.tsbuildinfo"

  log "finished"
}

main "$@"