#compdef haj

_haj_installed_packages() {
    if (( $+commands[pacman] )); then
        compadd $(pacman -Qq 2>/dev/null)
    elif (( $+commands[dpkg-query] )); then
        compadd $(dpkg-query -W -f='${Package}\n' 2>/dev/null)
    elif (( $+commands[rpm] )); then
        compadd $(rpm -qa --qf '%{NAME}\n' 2>/dev/null)
    fi
}

_haj_all_packages() {
    if (( $+commands[pacman] )); then
        compadd $(pacman -Slq 2>/dev/null)
    elif (( $+commands[apt-cache] )); then
        compadd $(apt-cache pkgnames 2>/dev/null)
    elif (( $+commands[dnf5] )); then
        compadd $(dnf5 -C -q repoquery --qf '%{name}\n' 2>/dev/null)
    elif (( $+commands[dnf] )); then
        compadd $(dnf -C -q repoquery --qf '%{name}\n' 2>/dev/null)
    fi
}

_haj_groups() {
    if (( $+commands[pacman] )); then
        compadd $(pacman -Sg 2>/dev/null)
    elif (( $+commands[dnf5] )); then
        compadd $(dnf5 -C -q group list 2>/dev/null | awk 'NR>1 {print $1}')
    elif (( $+commands[dnf] )); then
        compadd $(dnf -C -q group list --ids 2>/dev/null | sed -n 's/.*(\([^)]*\)).*/\1/p')
    fi
}

_haj_downgrades() {
    local -a pkgs
    if [[ -d /var/cache/pacman/pkg ]]; then
        pkgs+=($(ls /var/cache/pacman/pkg/ 2>/dev/null | grep -E '\.pkg\.tar\.(zst|xz|gz)$' | sed -E 's/-[^-]+-[^-]+-[^-]+\.pkg\.tar\..*$//'))
    fi
    if [[ -d ~/.cache/haj/aur ]]; then
        pkgs+=($(ls ~/.cache/haj/aur/ 2>/dev/null))
    fi
    if [[ -d /var/cache/apt/archives ]]; then
        pkgs+=($(find /var/cache/apt/archives -maxdepth 1 -type f -name '*.deb' 2>/dev/null | xargs -r -n1 basename | sed -E 's/_[^_]+_[^_]+\.deb$//'))
    fi
    if [[ -d /var/cache/libdnf5 || -d /var/cache/dnf ]]; then
        pkgs+=($(find /var/cache/libdnf5 /var/cache/dnf -type f -name '*.rpm' 2>/dev/null | xargs -r -n1 basename | sed -E 's/-[^-]+-[^-]+\.[^.]+\.rpm$//'))
    fi
    compadd ${(u)pkgs}
}

_haj() {
    local curcontext="$curcontext" state line
    typeset -A opt_args

    _arguments -C \
        '(-a --aur)'{-a,--aur}'[restrict operations to the aur]' \
        '(-r --repo)'{-r,--repo}'[restrict operations to arch repositories]' \
        '--from[restrict operations to source]:source:(aur repo repos)' \
        '(-y --noconfirm)'{-y,--noconfirm}'[bypass all confirmation prompts]' \
        '(-n --needed)'{-n,--needed}'[do not reinstall up-to-date packages]' \
        '(-i --ignore)'{-i,--ignore}'[ignore a package upgrade]' \
        '(-c --config)'{-c,--config}'[specify an alternate pacman config file]:config file:_files' \
        '--root[specify an alternate installation root]:root dir:_files -/' \
        '(-v --verbose)'{-v,--verbose}'[enable verbose debug logging]' \
        '(-d --dry-run)'{-d,--dry-run}'[preview a command without modifying the system]' \
        '(-V --version)'{-V,--version}'[show version info]' \
        '(-h --help)'{-h,--help}'[display help message]' \
        '1: :->cmds' \
        '*:: :->args'

    case $state in
        cmds)
            local -a subcmds
            subcmds=(
                'tui:launch interactive package manager dashboard'
                'update:synchronize remote repositories'
                'upgrade:full system upgrade'
                'install:install one or more packages'
                'add:install one or more packages'
                'remove:remove packages & unneeded dependencies'
                'search:search remote repositories'
                'show:show detailed package information'
                'group:browse and install package groups'
                'list:list installed packages'
                'stats:show system health and package statistics'
                'load:install a local package archive'
                'fetch:download a package without installing'
                'downgrade:downgrade an installed package'
                'owns:find which installed package owns a file'
                'files:list files installed by a package'
                'locate:search repositories for a file'
                'history:show recent package changes'
                'orphan:detect orphaned dependencies'
                'clean:clean the package cache'
                'mark:change a package install reason'
                'diff:interactively manage and merge .pacnew files'
                'pkgbuild:read and print the PKGBUILD file of a package from the AUR'
            )
            _describe -t commands 'haj commands' subcmds
            ;;
        args)
            case $words[1] in
                install|add|i|a|fetch|f|download|get|pkgbuild|pb)
                    _haj_all_packages
                    ;;
                remove|rm|toss|uninstall|delete|drop|mark|m|show|info|about|describe|files|lf)
                    _haj_installed_packages
                    ;;
                downgrade|sink|rollback)
                    _haj_downgrades
                    ;;
                group|g)
                    _haj_groups
                    ;;
                load|l)
                    _files -g "*.(pkg.tar.zst|pkg.tar.xz|pkg.tar.gz|deb|rpm)"
                    ;;
                owns|ow)
                    _files
                    ;;
                list|ls)
                    _arguments \
                        '(-e --explicit)'{-e,--explicit}'[show only explicitly installed packages]' \
                        '(-p --deps)'{-p,--deps}'[show only dependencies]' \
                        '(-f --foreign)'{-f,--foreign}'[show only foreign/aur packages]'
                    ;;
                clean|c)
                    _arguments \
                        '(-k --keep)'{-k,--keep}'[number of package versions to keep]'
                    ;;
                history|h)
                    _arguments \
                        '(-l --limit)'{-l,--limit}'[number of recent changes to show]'
                    ;;
                upgrade|jump)
                    _arguments \
                        '--no-sync[do not sync remote repositories first]'
                    ;;
            esac
            ;;
    esac
}

compdef _haj haj
