#!/usr/bin/env bash
# twd: destroy a sibling git worktree and its canonical tmux session.

set -euo pipefail

usage() {
  echo "Usage: twd <name-or-path>" >&2
}

current_session_name() {
  local tmux_bin="$1"

  if [[ -z "${TMUX:-}" ]]; then
    return 1
  fi

  "$tmux_bin" display-message -p '#{session_name}' 2>/dev/null
}

resolve_target_path() {
  local raw_target="$1"
  local checkout_root="$2"
  local repo_stem="$3"
  local sibling_dir
  local target_name

  if [[ -e "$raw_target" ]]; then
    cd "$raw_target" >/dev/null 2>&1 && pwd -P
    return 0
  fi

  sibling_dir=$(dirname -- "$checkout_root")

  if [[ "$raw_target" == */* ]]; then
    echo "error: worktree path not found: $raw_target" >&2
    return 1
  fi

  target_name=$(sanitize_component "$raw_target")
  if [[ -z "$target_name" ]]; then
    echo "error: empty worktree name after sanitization" >&2
    return 1
  fi

  if [[ "$target_name" != "$repo_stem" && "$target_name" != "${repo_stem}-"* ]]; then
    target_name="${repo_stem}-${target_name}"
  fi

  printf '%s/%s\n' "$sibling_dir" "$target_name"
}

if [[ ${1:-} == "-h" || ${1:-} == "--help" ]]; then
  usage
  exit 0
fi

if [[ $# -ne 1 ]]; then
  usage
  exit 1
fi

script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
lib_path="$script_dir/tmux-lib.sh"
root_helper="${TMUX_PROJECT_ROOT_BIN:-$script_dir/tmux-project-root}"
name_helper="${TMUX_PROJECT_NAME_BIN:-$script_dir/tmux-project-name}"
tmux_bin="${TMUX_BIN:-tmux}"

# shellcheck source=bin/tmux-lib.sh
source "$lib_path"

checkout_root=$($root_helper .)
repo_stem=$(resolve_repo_stem "$checkout_root")
target_path=$(resolve_target_path "$1" "$checkout_root" "$repo_stem")

if [[ ! -d "$target_path" ]]; then
  echo "error: worktree path not found: $target_path" >&2
  exit 1
fi

session_name=$($name_helper "$target_path")

if "$tmux_bin" has-session -t "$session_name" 2>/dev/null; then
  if current_session=$(current_session_name "$tmux_bin"); then
    if [[ "$current_session" == "$session_name" ]]; then
      echo "error: refusing to remove the current tmux session: $session_name" >&2
      exit 1
    fi
  fi

  "$tmux_bin" kill-session -t "$session_name"
fi

git -C "$checkout_root" worktree remove "$target_path"
