#!/usr/bin/env bash
# cleanup-worktree.sh —— 删除一个 worktree 及其附属资源
#
# 默认会清理：
#   1. git worktree remove
#   2. 独立 PostgreSQL Docker 容器（ffws-wt-pg-<port>）
#   3. （若配置）从个人 Caddy 配置中移除该 worktree 的域名段并 reload
#
# 用法:
#   bash scripts/dev/cleanup-worktree.sh <worktree-path>
#   bash scripts/dev/cleanup-worktree.sh <worktree-path> --keep-db   # 保留 Docker 容器
#   bash scripts/dev/cleanup-worktree.sh <worktree-path> --force     # 即使有未提交改动也删

set -euo pipefail

if [[ $# -lt 1 ]]; then
  cat <<'EOF'
用法: bash scripts/dev/cleanup-worktree.sh <worktree-path> [--keep-db] [--force]

参数:
  worktree-path  要删除的 worktree 目录路径
  --keep-db      保留独立 PostgreSQL 容器（默认会一起删）
  --force        即使有未提交改动也强制删（git worktree remove --force）
EOF
  exit 1
fi

WORKTREE_PATH="$1"
shift || true
KEEP_DB=false
FORCE=false
for arg in "$@"; do
  case "${arg}" in
    --keep-db) KEEP_DB=true ;;
    --force) FORCE=true ;;
    *) echo "未知参数: ${arg}" >&2; exit 1 ;;
  esac
done

if [[ ! -d "${WORKTREE_PATH}" ]]; then
  echo "cleanup-worktree: 目录不存在: ${WORKTREE_PATH}" >&2
  exit 1
fi

ROOT_DIR="$(git rev-parse --show-toplevel)"
SHORT_NAME="$(basename "${WORKTREE_PATH}")"

# ---------- 1. 读取端口（从 worktree 的 .env） ----------
WT_DB_PORT=""
WT_REDIS_PORT=""
if [[ -f "${WORKTREE_PATH}/.env" ]]; then
  WT_DB_PORT="$(grep -E '^POSTGRES_PORT=' "${WORKTREE_PATH}/.env" | head -1 | cut -d= -f2 || true)"
  WT_REDIS_PORT="$(grep -E '^REDIS_PORT=' "${WORKTREE_PATH}/.env" | head -1 | cut -d= -f2 || true)"
fi

# ---------- 2. 移除 Caddy 域名段（若存在个人配置） ----------
# 兼容两种 marker 格式：
#   - 新格式（setup-worktree.sh 自动注入）：# >>> ffoa-worktree:<name>:<user> >>> ... # <<< ... <<<
#   - 老格式（手动追加遗留）：# worktree: <name> (<user>) — added <date>，下接 <name>.<user>.<base> { ... }
caddy_remove_block() {
  local file="$1"
  local removed=0
  # 新格式：marker 包夹的多行块
  local marker_begin="# >>> ffoa-worktree:${SHORT_NAME}:${USER} >>>"
  local marker_end="# <<< ffoa-worktree:${SHORT_NAME}:${USER} <<<"
  if grep -qF "${marker_begin}" "${file}"; then
    sed -i "/${marker_begin//\//\\/}/,/${marker_end//\//\\/}/d" "${file}"
    removed=1
  fi
  # 老格式：手动追加的 `# worktree: <name>` 单行注释 + 紧跟一个完整 site block（含嵌套花括号）
  # 用 awk 做花括号配平：匹配到注释后的 `{` 算 +1，遇到 `}` 算 -1，归零即段落结束
  local domain_pattern="^${SHORT_NAME}\\.${USER}\\."
  if grep -qE "^# worktree:[[:space:]]+${SHORT_NAME}[[:space:]]+\\(${USER}\\)" "${file}" || \
     grep -qE "${domain_pattern}" "${file}"; then
    awk -v name="${SHORT_NAME}" -v user="${USER}" '
      BEGIN { skipping=0; depth=0 }
      skipping == 0 && $0 ~ "^# worktree:[[:space:]]+" name "[[:space:]]+\\(" user "\\)" {
        skipping=1; next
      }
      skipping == 0 && $0 ~ "^" name "\\." user "\\.[^[:space:]]+[[:space:]]*\\{[[:space:]]*$" {
        skipping=1; depth=1; next
      }
      skipping == 1 {
        n_open  = gsub(/\{/, "{")
        n_close = gsub(/\}/, "}")
        depth += n_open - n_close
        if (depth <= 0) { skipping=0; next }
        next
      }
      { print }
    ' "${file}" > "${file}.tmp" && mv "${file}.tmp" "${file}"
    removed=1
  fi
  return $((1 - removed))
}

if [[ -n "${FFOA_DEV_DOMAIN_BASE:-}" && -n "${FFOA_DEV_CADDY_FILE:-}" && -w "${FFOA_DEV_CADDY_FILE}" ]]; then
  if caddy_remove_block "${FFOA_DEV_CADDY_FILE}"; then
    echo "cleanup-worktree: Caddy 配置已移除域名段"
    if [[ -n "${FFOA_DEV_CADDY_RELOAD_CMD:-}" ]]; then
      eval "${FFOA_DEV_CADDY_RELOAD_CMD}" >/dev/null 2>&1 \
        && echo "cleanup-worktree: Caddy 已 reload" \
        || echo "cleanup-worktree: ⚠️  Caddy reload 失败"
    fi
  fi
fi

# ---------- 3. git worktree remove ----------
if [[ "${FORCE}" == "true" ]]; then
  git -C "${ROOT_DIR}" worktree remove --force "${WORKTREE_PATH}"
else
  git -C "${ROOT_DIR}" worktree remove "${WORKTREE_PATH}"
fi
echo "cleanup-worktree: git worktree 已移除"

# ---------- 4. 删 PostgreSQL 容器 ----------
if [[ "${KEEP_DB}" == "false" && -n "${WT_DB_PORT}" ]]; then
  container="ffws-wt-pg-${WT_DB_PORT}"
  if docker ps -a --format '{{.Names}}' | grep -qx "${container}"; then
    docker rm -f "${container}" >/dev/null
    echo "cleanup-worktree: PostgreSQL 容器已删除: ${container}"
  fi
  # Redis 容器：兼容两种命名
  #   新格式（setup-worktree.sh 自动）：ffws-wt-redis-<port>
  #   老格式（早期手动起的遗留）：     ffoa-wt-<short_name>-redis
  redis_candidates=()
  [[ -n "${WT_REDIS_PORT}" ]] && redis_candidates+=("ffws-wt-redis-${WT_REDIS_PORT}")
  redis_candidates+=("ffoa-wt-${SHORT_NAME}-redis")
  for c in "${redis_candidates[@]}"; do
    if docker ps -a --format '{{.Names}}' | grep -qx "${c}"; then
      docker rm -f "${c}" >/dev/null
      echo "cleanup-worktree: Redis 容器已删除: ${c}"
    fi
  done
fi

echo ""
echo "✅ worktree 已清理完成: ${WORKTREE_PATH}"
