# Bash completion for zoryn using cmdliner completion protocol
# Source this file from ~/.bashrc or ~/.bash_completion

# Parse cmdliner completion protocol output
# Returns: space-separated list of completion items
_zoryn_parse_protocol() {
    local output="$1"
    local items=()
    local in_item=0
    local item_name=""

    while IFS= read -r line; do
        case "$line" in
            item)
                in_item=1
                ;;
            item-end)
                if [[ -n "$item_name" ]]; then
                    items+=("$item_name")
                fi
                in_item=0
                item_name=""
                ;;
            files)
                # Signal to complete files
                echo "__FILES__"
                return
                ;;
            dirs)
                # Signal to complete directories
                echo "__DIRS__"
                return
                ;;
            *)
                if [[ $in_item -eq 1 && -z "$item_name" ]]; then
                    item_name="$line"
                fi
                ;;
        esac
    done <<< "$output"

    printf '%s\n' "${items[@]}"
}

# Get completions from zoryn using cmdliner protocol
_zoryn_get_completions() {
    local token="$1"
    shift
    local args=("$@")

    # Build command line for completion
    local output
    output=$(zoryn --__complete "${args[@]}" "--__complete=$token" 2>/dev/null)

    _zoryn_parse_protocol "$output"
}

# Note: Branch, arch, and builder completions are now provided by cmdliner
# via Arg.Completion API. Custom functions removed.

_zoryn() {
    local cur prev words cword

    # Use -n : to prevent splitting on colons (needed for @host:name patterns)
    if type _init_completion &>/dev/null; then
        _init_completion -n : || return
    else
        # Fallback without bash-completion framework:
        # Reconstruct current word from COMP_LINE to handle colons correctly
        COMPREPLY=()
        local comp_point=${COMP_POINT:-${#COMP_LINE}}
        local before_cursor="${COMP_LINE:0:$comp_point}"
        cur="${before_cursor##* }"
        prev="${COMP_WORDS[COMP_CWORD-1]:-}"
        words=("${COMP_WORDS[@]}")
        cword=$COMP_CWORD
    fi

    COMPREPLY=()

    # Handle special options that cmdliner doesn't know about
    # Note: -b, --builder, -a, --arch, --dry-run, --force are handled by cmdliner
    case "$prev" in
        --stage|--from)
            COMPREPLY=($(compgen -W "detect fetch find-version merge merge-hooks spec gear-tags up-hooks build batch-build" -- "${cur}"))
            return 0
            ;;
        --multi-add|--start-number|-n|--number)
            # Common hasher/builder numbers (1-128 range)
            COMPREPLY=($(compgen -W "1 2 3 4 5 10 20 50" -- "$cur"))
            return 0
            ;;
        --type)
            COMPREPLY=($(compgen -W "local remote" -- "$cur"))
            return 0
            ;;
        --dptype)
            COMPREPLY=($(compgen -W "source binary both" -- "$cur"))
            return 0
            ;;
        --tag)
            # Git tags
            if git rev-parse --git-dir &>/dev/null; then
                local tags
                tags=$(git tag -l 2>/dev/null)
                COMPREPLY=($(compgen -W "$tags" -- "$cur"))
            fi
            return 0
            ;;
        --batch)
            # Batch config files
            compopt -o filenames
            local batch_dir="$HOME/.config/zoryn/batch"
            if [[ -d "$batch_dir" ]]; then
                local configs
                configs=$(cd "$batch_dir" && ls -1 *.conf 2>/dev/null | sed 's/\.conf$//')
                COMPREPLY=($(compgen -W "$configs" -- "$cur"))
            fi
            COMPREPLY+=($(compgen -f -X '!*.conf' -- "$cur"))
            COMPREPLY+=($(compgen -d -- "$cur"))
            return 0
            ;;
        --spec)
            # Spec file completion
            compopt -o filenames
            COMPREPLY=($(compgen -f -X '!*.spec' -- "$cur"))
            return 0
            ;;
        -l|--log-dir|--basedir|-o|--output|--hasher-dir|--remote-dir|--up)
            # Directory completion
            compopt -o filenames
            COMPREPLY=($(compgen -d -- "$cur"))
            return 0
            ;;
        --prefix)
            COMPREPLY=($(compgen -W "ocaml- python3-module- perl-" -- "$cur"))
            return 0
            ;;
    esac

    # Build args for cmdliner protocol (exclude current word)
    # Use words/cword from _init_completion when available (colon-aware)
    local args=()
    for ((i=1; i < cword; i++)); do
        args+=("${words[i]}")
    done

    # Get completions from cmdliner protocol
    local completions
    completions=$(_zoryn_get_completions "$cur" "${args[@]}")

    case "$completions" in
        __FILES__)
            compopt -o filenames
            COMPREPLY=($(compgen -f -- "$cur"))
            return 0
            ;;
        __DIRS__)
            compopt -o filenames
            COMPREPLY=($(compgen -d -- "$cur"))
            return 0
            ;;
    esac

    # Filter completions by current prefix
    if [[ -n "$completions" ]]; then
        COMPREPLY=($(compgen -W "$completions" -- "$cur"))
    fi

    # Handle colon prefix trimming for bash-completion compatibility
    if type __ltrim_colon_completions &>/dev/null; then
        __ltrim_colon_completions "$cur"
    fi

    return 0
}

complete -F _zoryn zoryn
