# shellcheck shell=bash

cmd_checkout_worktree() {
    local create_new=false
    local branch_name=""
    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 [[ "${1-}" == "-b" ]]; then
        [[ -z "${2-}" ]] && { err "Branch name required for -b"; echo "Usage: gw checkout -b <branch>"; return 1; }
        create_new=true
        branch_name="$2"
        [[ "$#" -gt 2 ]] && { err "Too many args"; return 1; }
    else
        [[ -z "${1-}" ]] && { err "Branch name required"; echo "Usage: gw checkout <branch>"; return 1; }
        branch_name="$1"
        [[ "$#" -gt 1 ]] && { err "Too many args"; return 1; }
    fi

    if $create_new; then
        if git_branch_exists "$branch_name"; then
            # Branch exists, ensure worktree exists
            local wt; wt="$(git_branch_to_worktree_path "$branch_name")"
            if [[ -n "$wt" ]]; then
                info "✅ Worktree exists at '$wt'"
                echo "cd \"$wt\""
            else
                # Create worktree for existing branch
                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"
                echo "cd \"$wt\""
            fi
            return 0
        else
            # Create new branch and worktree
            cmd_create_worktree "$branch_name" || return $?
            local wt; wt="$(git_branch_to_worktree_path "$branch_name")"
            [[ -n "$wt" ]] && {
                echo "cd \"$wt\""
                return 0
            }
            err "Worktree created but not found"
            return 1
        fi
    else
        # Switch to existing branch
        local wt; wt="$(git_branch_to_worktree_path "$branch_name")"
        if [[ -n "$wt" ]]; then
            echo "cd \"$wt\""
            return 0
        fi

        # Try to create worktree for existing branch
        if git_branch_exists "$branch_name"; 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"
            echo "cd \"$wt\""
            return 0
        else
            err "Branch '$branch_name' does not exist"
            return 1
        fi
    fi
}
