#!/usr/bin/env bash

setup-completion() {
    local shell_type="$1"

    # "help" is a pseudo-shell-type: print setup instructions for every
    # supported shell and skip emitting any completion script at all.
    if [[ "$shell_type" == "help" ]]; then
        echo ""
        show-completion-instructions "bash"
        show-completion-instructions "zsh"
        show-completion-instructions "fish"
        return 0
    fi

    # Remember whether the caller actually passed a shell type,
    # since we only want to print setup instructions when they didn't.
    local shell_type_given=1
    [[ -z "$shell_type" ]] && shell_type_given=0

    # Validate shell type
    case "$shell_type" in
        bash|zsh|fish)
            # Valid shell type
            ;;
        *)
            echo "Error: Unsupported shell type '$shell_type'. Use 'bash', 'zsh', 'fish', or 'help'."
            echo "Usage: task setup-completion [bash|zsh|fish|help]"
            return 1
            ;;
    esac

    # Output the actual completion script
    output_completion_script "$shell_type"

    # Only show setup instructions when no shell type was explicitly given.
    # When the caller specifies a shell type (e.g. for piping/redirecting
    # straight into a rc file), keep the output clean of comment noise.
    if [[ "$shell_type_given" == "0" ]]; then
        echo ""
        show-completion-instructions "$shell_type"
    fi
}

show-completion-instructions() {
    local shell_type="$1"

    echo "Taskfile completion setup instructions ($shell_type):"
    echo ""
    echo "To enable completion, add this script to your shell configuration:"

    if [[ "$shell_type" == "fish" ]]; then
        echo "  task setup-completion fish >> ~/.config/fish/config.fish"
        echo "  source ~/.config/fish/config.fish"
    elif [[ "$shell_type" == "zsh" ]]; then
        echo "  task setup-completion zsh >> ~/.zshrc"
        echo "  source ~/.zshrc"
    else
        echo "  task setup-completion bash >> ~/.bashrc"
        echo "  source ~/.bashrc"
    fi
    echo ""
    echo "---"
    echo ""
}

output_completion_script() {
    local shell_type="$1"

    # Default to bash if no shell type provided
    if [[ -z "$shell_type" ]]; then
        shell_type="bash"
    fi

    if [[ "$shell_type" == "fish" ]]; then
        # Fish completion script
        cat << 'EOF'
# Taskfile completion for fish

function __task_commands
    task help 2>/dev/null | grep -A100 -e '---' | awk '{print $2}' | sed 's/^[[:space:]]*//' | grep -v '^$'
end

# First argument position: offer the list of task commands.
complete -c task -f -n '__fish_use_subcommand' -a '(__task_commands)'
complete -c t    -f -n '__fish_use_subcommand' -a '(__task_commands)'

# Once a command has already been typed, fall back to file completion.
complete -c task -f -n 'not __fish_use_subcommand' -a '(__fish_complete_path)'
complete -c t    -f -n 'not __fish_use_subcommand' -a '(__fish_complete_path)'
EOF
    elif [[ "$shell_type" == "zsh" ]]; then
        # ZSH completion script
        cat << 'EOF'
# Taskfile completion for zsh
_task_completions() {
    local -a reply
    local si=$IFS

    # $CURRENT is zsh's 1-indexed equivalent of bash's COMP_CWORD.
    # CURRENT == 2 means we're completing the first argument after `task`/`t`.
    if [[ $CURRENT -eq 2 ]]; then
        IFS=$'\n' reply=($(task help | grep -A999 -e '---' | awk '{print $2}' | sed 's/^[[:space:]]*//' | grep -v '^$'))
        IFS=$si
        if (( ${#reply} > 0 )); then
            _describe 'task' reply
        else
            _default
        fi
    else
        _files
    fi
}

compdef _task_completions task
compdef _task_completions t
EOF
    else
        # Bash completion script
        cat << 'EOF'
# Taskfile completion for bash
_task_completions() {
    local cur prev commands
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # compgen -W wants a single space-separated string, so tr is fine here.
    commands=$(task help | grep -A999 -e '---' | awk '{print $2}' | sed 's/^[[:space:]]*//' | grep -v '^$' | tr '\n' ' ')

    if [[ ${COMP_CWORD} == 1 ]]; then
        COMPREPLY=( $(compgen -W "${commands}" -- "${cur}") )
    elif [[ ${COMP_CWORD} == 2 ]]; then
        COMPREPLY=( $(compgen -f -- "${cur}") )
    else
        COMPREPLY=()
    fi
}

complete -F _task_completions task
complete -F _task_completions t
EOF
    fi
}