#!/bin/bash

set -eu
set -o pipefail

ARGS=("${@-}")
TMP_FILE="/tmp/aicommit"

pushd "$(pwd)" >/dev/null || exit 1

spin() {
	echo "${@}"
	while true; do
		spinner=('-' '\' '|' '/')
		for i in "${spinner[@]}"; do
			echo -ne "\r${i}"
			sleep .05
		done
	done
	echo ""
}

if [[ -z ${GROQ_API_KEY} ]]; then
	echo "API key not set."
	exit 1
fi

system="You are an expert programmer that values clear, unambiguous communication and are specialized in generating concise and informative git commit messages. Only reply with the commit message and nothing else."

if ! diff=$(git diff --cached); then
	echo "Failed to get diff."
	exit 1
fi

message=$(
	jq -n \
		".messages = [{role: \"system\", content: $(jq -R -s '@json' <<<"$system")}, {role: \"user\", content: $(jq -R -s '@json' <<<"$diff")}] |
   .model = \"llama-3.1-70b-versatile\" |
   .temperature = 1 |
   .max_tokens = 1024 |
   .top_p = 1 |
   .stream = false |
   .stop = null"
)
spin "AI is thinking..." &
SPINNER="$!"
curl -s "https://api.groq.com/openai/v1/chat/completions" \
	-X POST \
	-H "Content-Type: application/json" \
	-H "Authorization: Bearer ${GROQ_API_KEY}" \
	-d "${message}" | jq -r '.choices[0].message.content | gsub("\""; "")' >"${TMP_FILE}"

if [[ 0 -ne $? ]]; then
	echo "Failed to get response."
	kill "${SPINNER}"
	exit 1
fi
kill "${SPINNER}"

git commit -e -m "$(cat ${TMP_FILE})" && rm ${TMP_FILE}

popd >/dev/null || exit 1