# shellcheck shell=bash

cmd_new_tmux_session_with_command() {
  local branch_name="$1"
  local command_line="$2"

  local root; root="$(git_require_repo_root)" || return 1
  local shared_root; shared_root="$(git_shared_root 2>/dev/null)"
  [[ -z "$shared_root" ]] && shared_root="$root"
  local source_root="$root"

  if ! tmux_available; then
    err "tmux not installed"
    return 1
  fi

  if [[ -z "$branch_name" ]]; then
    err "Branch name required"
    return 1
  fi

  if [[ -z "${command_line// }" ]]; then
    err "Command required"
    return 1
  fi

  local wt=""
  if git_branch_exists "$branch_name"; then
    wt="$(git_branch_to_worktree_path "$branch_name")"
    if [[ -z "$wt" ]]; then
      info "🌳 Creating worktree for existing branch '$branch_name'..."
      wt="$(git_ensure_worktree_for_branch "$branch_name")"
      gw_env_copy_files "$source_root" "$wt" "$shared_root"
    fi
  else
    err "Branch '$branch_name' does not exist"
    return 1
  fi

  if [[ -z "$wt" ]]; then
    err "Worktree not found for branch '$branch_name'"
    return 1
  fi

  local session=""
  session="$(tmux_ensure_session "$branch_name" "" "$wt")" || return 1
  if [[ -z "$session" ]]; then
    err "Failed to create tmux session"
    return 1
  fi

  tmux_send_keys "$session" "$command_line" || return 1
  tmux_attach_session "$session"
}
