#!/usr/bin/env bash

set -euo pipefail

TAG_LIMIT="${PIJUL_RECORD_TAG_LIMIT:-500}"

usage() {
    cat <<'EOF'
Use previously seen intent tags while creating a new Pijul change.

Usage:
  scripts/pijul-record-with-intent-tags [pijul record options and prefixes...]
  scripts/pijul-record-with-intent-tags --list-tags

Behavior:
  - Extracts recent intent tags from `pijul log`.
  - Uses `fzf` for interactive selection when available.
  - Otherwise prints known tags as a reminder and asks for the message body.
  - If `-m/--message` is already provided, it prints known tags and forwards
    directly to `pijul record`.

Environment:
  PIJUL_RECORD_TAG_LIMIT  Number of recent log entries to scan (default: 500)
EOF
}

has_message_arg() {
    local arg

    for arg in "$@"; do
        case "$arg" in
            --)
                return 1
                ;;
            -m|--message|--message=*|-m?*)
                return 0
                ;;
        esac
    done

    return 1
}

collect_intent_tags() {
    pijul log --limit "$TAG_LIMIT" 2>/dev/null \
        | sed -nE 's/^    ([[:alnum:]_-]+\([^)]*\)).*/\1/p' \
        | awk 'NF && !seen[$0]++'
}

join_lines() {
    awk '
        NR == 1 { printf "%s", $0; next }
        { printf ", %s", $0 }
        END { if (NR > 0) printf "\n" }
    '
}

print_known_tags() {
    local tags="$1"

    if [[ -z "$tags" ]]; then
        return
    fi

    printf 'Known tags: %s\n' "$(printf '%s\n' "$tags" | join_lines)" >&2
}

select_tag() {
    local tags="$1"

    if [[ -z "$tags" || ! -t 0 ]]; then
        return
    fi

    if command -v fzf >/dev/null 2>&1; then
        printf '%s\n' "$tags" \
            | fzf --prompt='intent tag (Esc=skip)> ' --height=40% --reverse \
            || true
        return
    fi

    print_known_tags "$tags"
}

main() {
    local tags=""
    local tag=""
    local body=""
    local message=""

    case "${1-}" in
        --help|-h)
            usage
            exit 0
            ;;
        --list-tags)
            collect_intent_tags || true
            exit 0
            ;;
    esac

    tags="$(collect_intent_tags || true)"

    if has_message_arg "$@"; then
        if [[ -t 1 ]]; then
            print_known_tags "$tags"
        fi

        exec pijul record "$@"
    fi

    if [[ ! -t 0 ]]; then
        printf 'This helper needs a terminal unless you pass -m/--message.\n' >&2
        exit 1
    fi

    tag="$(select_tag "$tags")"
    tag="${tag%%$'\n'*}"
    tag="${tag%$'\r'}"

    if [[ -n "$tag" ]]; then
        printf 'Using tag: %s\n' "$tag" >&2
    fi

    read -erp "message: " body < /dev/tty

    if [[ -n "$tag" && -n "$body" ]]; then
        message="$tag: $body"
    elif [[ -n "$tag" ]]; then
        message="$tag"
    else
        message="$body"
    fi

    if [[ -z "$message" ]]; then
        printf 'Change message cannot be empty.\n' >&2
        exit 1
    fi

    exec pijul record -m "$message" "$@"
}

main "$@"