# bash completion for user-installed-packages

_user_installed_packages() {
    local cur prev words cword
    _init_completion || return

    local all_opts="
        --generate --install --cli --help --version
        -g -i -c -h -v
        --file --output
        -f -o
    "

    case "$prev" in
        -f|--file)
            if [[ " ${words[*]} " =~ " -i " || " ${words[*]} " =~ " --install " ]]; then
                if [[ -z "$cur" ]]; then
                    # nothing typed: suggest uip-list-*.txt in cwd; fall back to all
                    COMPREPLY=($(compgen -f -X '!uip-list-*.txt' -- ""))
                    [[ ${#COMPREPLY[@]} -eq 0 ]] && COMPREPLY=($(compgen -f -- ""))
                elif [[ "$cur" == */ || -d "$cur" ]]; then
                    # directory typed: suggest uip-list-*.txt inside it; fall back to all
                    local dir="${cur%/}/"
                    COMPREPLY=($(compgen -f -- "${dir}uip-list-"))
                    [[ ${#COMPREPLY[@]} -eq 0 ]] && COMPREPLY=($(compgen -f -- "$cur"))
                else
                    # partial filename: complete anything matching
                    COMPREPLY=($(compgen -f -- "$cur"))
                    # single directory match: look inside for uip-list-* immediately (saves one Tab)
                    if [[ ${#COMPREPLY[@]} -eq 1 && -d "${COMPREPLY[0]}" ]]; then
                        local dir="${COMPREPLY[0]%/}/"
                        local inner=($(compgen -f -- "${dir}uip-list-"))
                        if [[ ${#inner[@]} -gt 0 ]]; then
                            COMPREPLY=("${inner[@]}")
                        else
                            COMPREPLY=("$dir")
                        fi
                    fi
                fi
            else
                # --generate: any file, or - for stdout
                COMPREPLY=($(compgen -W "-" -- "$cur"))
                COMPREPLY+=($(compgen -f -- "$cur"))
            fi
            return ;;
        -o|--output)
            _filedir -d
            return ;;
    esac

    COMPREPLY=($(compgen -W "$all_opts" -- "$cur"))
}

complete -o filenames -F _user_installed_packages user-installed-packages
complete -o filenames -F _user_installed_packages uip
