#!/bin/sh

set -eu

if [ $# -lt 1 ] || [ $# -gt 2 ]; then
    echo "Usage: $0 DIR [SINCE [UNTIL]]"
    exit 1
fi

readonly DIR="$1"; shift

if [ $# -gt 0 ]; then
    SINCE="$(date -d "$1" +%Y-%m-%d)"; readonly SINCE
else
    SINCE="$(date +%Y-%m-01)"; readonly SINCE
fi

if [ $# -gt 1 ]; then
    UNTIL="$(date -d "$2" +%Y-%m-%d)"; readonly UNTIL
else
    UNTIL="$(date -d "${SINCE} + 1 month - 1 day" +%Y-%m-%d)"; readonly UNTIL
fi

PROMPT=$(cat <<'EOF'
Write a summary of the following commit messages.
Do not refer to commits, instead write in a style suitable for a release note that non-technical people would understand.
The output format should be Markdown where the repository name and remote ULR should be the header as a link and bullit lists should use dashes (-).
EOF
)
readonly PROMPT

summarize() {
    repo_dir=$1
    since=$2
    until=$3

    commits="$(git -C "$repo_dir" log --since="$since" --until="$until" --pretty=format:"%s")"

    if [ -n "$commits" ]; then
        echo >&2 "The repository in ${repo_dir} is being summarized."

        repo_name="$(basename "$repo_dir")"
        remote_url="$(git -C "$repo_dir" remote get-url origin)"
        content="$(printf "%s\nRepository name: %s\nRemote URL: %s\nCommit messages:\n%s" \
                          "$PROMPT" "$repo_name" "$remote_url" "$(echo "$commits" | sed 's/^/- /')")"
        json="{ \"model\": \"${OPENAI_CHAT_MODEL_ID}\",
                \"messages\": [{ \"role\": \"user\",
                                 \"content\": \"$( echo "$content" | sed ':a;N;$!ba;s/\n/\\n/g')\" }]}"
        tmpfile="$(mktemp)"; trap 'rm -f -- "$tmpfile"' EXIT

        curl -s "${OPENAI_BASE_URL}/chat/completions" \
             -H 'Content-Type: application/json' \
             -H "Authorization: Bearer ${OPENAI_API_KEY}" \
             -d "$json" | tee "$tmpfile" | jq -r ".choices[0].message.content"

        [ -n "${DEBUG:-}" ] && jq >&2 . "$tmpfile"

        echo
    else
        echo >&2 "The repository in ${repo_dir} contains no commits for the period, skipping."
    fi
}

echo >&2 "Generating summary for period: ${SINCE}...${UNTIL}"

find "$DIR" -type d -name .git -prune -print | sed 's|/\.git$||' | sort | while read -r repo_dir; do
    if [ -f "${repo_dir}/.no-git-summary" ]; then
        echo >&2 "The repository in ${repo_dir} is configured with no-git-summary, skipping."
        continue
    fi
    summarize "$repo_dir" "$SINCE" "$UNTIL"
done
