#compdef zoryn
# Zsh completion for zoryn using cmdliner completion protocol
# Install: copy to /usr/share/zsh/site-functions/_zoryn or add to fpath

# Parse cmdliner completion protocol and add completions
_zoryn_parse_protocol() {
    local output="$1"
    local -a items
    local -a descriptions
    local in_item=0
    local item_name=""
    local item_desc=""
    local current_group=""

    while IFS= read -r line; do
        case "$line" in
            1)
                # Protocol version, skip
                ;;
            group)
                in_item=0
                ;;
            item)
                in_item=1
                item_name=""
                item_desc=""
                ;;
            item-end)
                if [[ -n "$item_name" ]]; then
                    # Clean ANSI codes from description
                    item_desc="${item_desc//\[01m/}"
                    item_desc="${item_desc//\[04m/}"
                    item_desc="${item_desc//\[m/}"
                    # Take first line of description
                    item_desc="${item_desc%%$'\n'*}"
                    # Escape colons and brackets for zsh
                    item_desc="${item_desc//:/\\:}"
                    item_desc="${item_desc//\[/\\[}"
                    item_desc="${item_desc//\]/\\]}"
                    if [[ -n "$item_desc" ]]; then
                        items+=("${item_name}:${item_desc}")
                    else
                        items+=("$item_name")
                    fi
                fi
                in_item=0
                item_name=""
                item_desc=""
                ;;
            files)
                echo "__FILES__"
                return
                ;;
            dirs)
                echo "__DIRS__"
                return
                ;;
            *)
                if [[ $in_item -eq 1 ]]; then
                    if [[ -z "$item_name" ]]; then
                        item_name="$line"
                    else
                        if [[ -n "$item_desc" ]]; then
                            item_desc="$item_desc $line"
                        else
                            item_desc="$line"
                        fi
                    fi
                else
                    current_group="$line"
                fi
                ;;
        esac
    done <<< "$output"

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

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

    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 curcontext="$curcontext" state line
    typeset -A opt_args

    # Get current word and previous words
    local cur="${words[CURRENT]}"
    local prev="${words[CURRENT-1]}"

    # Handle special options that cmdliner doesn't know about
    # Note: -b, --builder, -a, --arch, -B, --branch are now handled by cmdliner
    case "$prev" in
        --stage|--from)
            local -a stages
            stages=(detect fetch find-version merge merge-hooks spec gear-tags up-hooks build batch-build)
            _describe -t stages 'pipeline stage' stages
            return
            ;;
        --type)
            _describe -t types 'builder type' '(local remote)'
            return
            ;;
        --dptype)
            _describe -t dptypes 'dependency type' '(source binary both)'
            return
            ;;
        --tag|-t)
            local -a tags
            if git rev-parse --git-dir &>/dev/null 2>&1; then
                tags=(${(f)"$(git tag -l 2>/dev/null)"})
                _describe -t tags 'git tag' tags
            fi
            return
            ;;
        --batch)
            local batch_dir="$HOME/.config/zoryn/batch"
            local -a configs
            if [[ -d "$batch_dir" ]]; then
                configs=(${batch_dir}/*.conf(N:t:r))
            fi
            _describe -t configs 'batch config' configs
            _files -g '*.conf'
            return
            ;;
        --spec)
            _files -g '*.spec'
            return
            ;;
        --prefix)
            _describe -t prefixes 'package prefix' '(ocaml- python3-module- perl-)'
            return
            ;;
    esac

    # Build args for cmdliner protocol
    local -a args
    for ((i=2; i < CURRENT; i++)); do
        args+=("${words[i]}")
    done

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

    case "$completions" in
        __FILES__)
            _files
            return
            ;;
        __DIRS__)
            _files -/
            return
            ;;
    esac

    if [[ -n "$completions" ]]; then
        local -a items
        items=(${(f)completions})

        # Check if we have descriptions (format: "name:description")
        if [[ "${items[1]}" == *:* ]]; then
            _describe -t completions 'zoryn' items
        else
            compadd -a items
        fi
    fi
}

_zoryn "$@"
