# Git Worktree Manager — Zsh integration
# Add to .zshrc: 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
                # Re-run to show Rich error output on stderr
                command gwtm cd "$2"
                return 1
            fi
            ;;
        *)
            command gwtm "$@"
            ;;
    esac
}

# Tab completion
_gwtm() {
    local -a subcmds
    subcmds=(
        'new:Create a new worktree'
        'ls:List worktrees'
        'rm:Remove a worktree'
        'cd:Change to a worktree directory'
        'path:Print worktree path'
        'clone:Clone a repo with gwtm setup'
        'sync:Sync worktree with base branch'
        'status:Show worktree status'
        'clean:Remove merged worktrees'
        'init-shell:Print shell integration code'
    )

    if (( CURRENT == 2 )); then
        _describe 'command' subcmds
    elif (( CURRENT == 3 )); then
        case "${words[2]}" in
            cd|rm|path|sync)
                local -a worktrees
                worktrees=($(command gwtm ls --names-only 2>/dev/null))
                if [[ "${words[2]}" == "cd" ]]; then
                    worktrees+=("main")
                fi
                _describe 'worktree' worktrees
                ;;
        esac
    fi
}

compdef _gwtm gwtm
