#!/usr/bin/env bash

set -euo pipefail

declare -A CHANGE_MESSAGES

resolve_message() {
    local hash="$1"

    if [[ -n "${CHANGE_MESSAGES[$hash]+x}" ]]; then
        printf '%s' "${CHANGE_MESSAGES[$hash]}"
        return
    fi

    local raw_message
    raw_message="$(pijul change "$hash" 2>/dev/null | sed -nE 's/^message = "(.*)"$/\1/p' | head -n 1 || true)"

    if [[ -z "$raw_message" ]]; then
        CHANGE_MESSAGES["$hash"]="<message unavailable>"
    else
        CHANGE_MESSAGES["$hash"]="${raw_message//\\\"/\"}"
    fi

    printf '%s' "${CHANGE_MESSAGES[$hash]}"
}

is_hash_line() {
    local line="$1"
    [[ "$line" =~ ^[A-Z0-9]+([[:space:]]*,[[:space:]]*[A-Z0-9]+)*$ ]]
}

format_hash_line() {
    local line="$1"
    local formatted=""
    local index=0
    local hash
    local message

    IFS=',' read -ra hashes <<< "$line"
    for hash in "${hashes[@]}"; do
        hash="${hash#"${hash%%[![:space:]]*}"}"
        hash="${hash%"${hash##*[![:space:]]}"}"

        message="$(resolve_message "$hash")"

        if (( index > 0 )); then
            formatted+=", "
        fi

        formatted+="${hash} (${message})"
        ((index += 1))
    done

    printf '%s\n' "$formatted"
}

while IFS= read -r line || [[ -n "$line" ]]; do
    if is_hash_line "$line"; then
        format_hash_line "$line"
    else
        printf '%s\n' "$line"
    fi
done < <(pijul credit "$@")