# Dynamic completion overrides for rsp play/queue arguments.

# Save clap-generated function so we can delegate non-dynamic cases.
functions[_rsp_clap]=$functions[_rsp]

_rsp() {
    case $words[2] in
        play|queue)
            _rsp_complete_args
            ;;
        *)
            _rsp_clap "$@"
            ;;
    esac
}

_rsp_complete_args() {
    setopt localoptions
    setopt nobanghist
    # Reconstruct full query from all argument words after subcommand.
    # This handles spaces in names (e.g. "Master of Puppets") that get
    # split across multiple $words entries when backslash escaping breaks.
    local -a args=("${(@)words[3,$CURRENT]}")
    local cur="${(j: :)args}"
    local -a suggestions
    local n_slashes=${#cur//[^\/]/}
    case $n_slashes in
        0) suggestions=(${(f)"$(rsp db-complete artists "$cur" 2>/dev/null)"}) ;;
        1) suggestions=(${(f)"$(rsp db-complete albums "$cur" 2>/dev/null)"}) ;;
        *) suggestions=(${(f)"$(rsp db-complete tracks "$cur" 2>/dev/null)"}) ;;
    esac
    # display: what the user sees in the completion menu (raw values)
    local -a display=("${suggestions[@]}")
    # vals: what gets inserted (with ZSH backslash escaping + ! escape)
    local -a vals=()
    local slash_idx=$cur[(I)/]
    local s
    for s in "${suggestions[@]}"; do
        local esc="${(q)s:gs/\!/\\\!/}"
        if (( slash_idx )); then
            local dir_part=$cur[1,$slash_idx]
            local edir="${(q)dir_part:gs/\!/\\\!/}"
            vals+=("${edir}${esc}")
        else
            vals+=("${esc}")
        fi
    done
    if (( ${#suggestions} )); then
        if [[ ${vals[1]} == */ ]]; then
            compadd -U -S '' -d display -- "${vals[@]}"
        else
            compadd -U -d display -- "${vals[@]}"
        fi
    fi
}
