#!/bin/bash

envList="ubuntu16.04 ubuntu18.04 ubuntu20.04 ubuntu22.04 ubuntu24.04 v10 v10sp1 shadow openkylin1.0 openkylin2.0"

function _kare() {
    local shortopts="-i -e -E -b -r -P -l -h -f"
    local longopts="install run inspect"
    local cur prev words cword

    COMPREPLY=()

    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD - 1]}"
    opts=$(kare -E)
    _init_completion -s || return

    local i=$cword

    # find the last option flag
    if [[ $cur != -* && $cur != install && $cur != remove && $cur != list && $cur != run && $cur != inspect ]]; then
        while [[ $prev != -* && $prev != install && $prev != remove && $prev != list && $prev != run && $prev != inspect && $i -ne 1 ]]; do
            prev=${words[--i - 1]}
        done
    fi

    case $prev in
    install | -i)
        _filedir '?(u|d)deb'
        return
        ;;
    remove | -L | -r | -P | -f | run | inspect)
        packagelist=()
        while IFS= read -r line; do
            # 清理 ANSI 转义码
            clean_line=$(echo "$line" | sed 's/\x1b\[[0-9;]*[a-zA-Z]//g')
            # 提取首列并标准化
            clean_col1=$(echo "$clean_line" | awk '{gsub(/^[[:space:]]+|[[:space:]]+$/,""); print $1}')
            # 过滤空行和潜在残留表头
            [[ -z $clean_col1 ]] && continue
            packagelist+=("$clean_col1")
        # 用 tail 跳过前2行表头
        done < <(kare -l 2>/dev/null | tail -n +3)
        
        set -f
        COMPREPLY=($(compgen -W "${packagelist[*]}" -- "$cur"))
        set +f
        return
        ;;
    -b)
        COMPREPLY=($(compgen -W "${envList}" -- "$cur"))
        return
        ;;
    -e)
        COMPREPLY=($(compgen -W "${opts}" -- "$cur"))
        return
        ;;
    kare)
        COMPREPLY=($(compgen -W "${shortopts} ${longopts}" -- "$cur"))
        return
        ;;
    esac
} &&
    complete -F _kare kare
