# Git Worktree Manager — Bash integration
# Add to .bashrc: eval "$(gwtm init-shell)"

gwtm() {
    case "$1" in
        cd)
            if [[ -z "$2" ]]; then
                echo "Usage: gwtm cd <name|main>" >&2
                return 1
            fi
            local dir
            dir=$(command gwtm cd "$2" 2>/dev/null)
            if [[ -n "$dir" && -d "$dir" ]]; then
                builtin cd "$dir"
            else
                command gwtm cd "$2"
                return 1
            fi
            ;;
        *)
            command gwtm "$@"
            ;;
    esac
}

# Tab completion
_gwtm_completions() {
    local cur prev subcmds
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    subcmds="new ls rm cd path clone sync status clean init-shell"

    if [[ ${COMP_CWORD} -eq 1 ]]; then
        COMPREPLY=($(compgen -W "${subcmds}" -- "${cur}"))
    elif [[ ${COMP_CWORD} -eq 2 ]]; then
        case "${prev}" in
            cd|rm|path|sync)
                local worktrees
                worktrees=$(command gwtm ls --names-only 2>/dev/null)
                if [[ "${prev}" == "cd" ]]; then
                    worktrees="${worktrees} main"
                fi
                COMPREPLY=($(compgen -W "${worktrees}" -- "${cur}"))
                ;;
        esac
    fi
}

complete -F _gwtm_completions gwtm
