if [ -n "$GIT_AICOMMIT_SKIP" ]; then
exit 0
fi
if ! command -v dotnet-aicommitmessage >/dev/null 2>&1; then
echo "Error: dotnet-aicommitmessage is not installed or not in PATH" >&2
echo "Please install it by running 'dotnet tool install -g aicommitmessage'" >&2
exit 1
fi
if [ -z "$1" ]; then
echo "Error: Commit message file not provided" >&2
exit 1
fi
COMMIT_MSG_FILE="$1"
if [ ! -f "$COMMIT_MSG_FILE" ]; then
echo "Error: Commit message file '$COMMIT_MSG_FILE' not found" >&2
exit 1
fi
CURRENT_MESSAGE=$(cat "$COMMIT_MSG_FILE")
cp "$COMMIT_MSG_FILE" "${COMMIT_MSG_FILE}.bak"
if ! AI_MESSAGE=$(dotnet-aicommitmessage generate-message -m "$CURRENT_MESSAGE" 2>/dev/null); then
echo "Error: Failed to generate AI commit message. Using original message." >&2
exit 0
fi
if [ -z "$AI_MESSAGE" ] || echo "$AI_MESSAGE" | grep -q '^[[:space:]]*$'; then
echo "Error: Generated commit message is empty." >&2
exit 1
fi
if ! echo "$AI_MESSAGE" > "$COMMIT_MSG_FILE" 2>/dev/null; then
echo "Error: Failed to write new commit message" >&2
cp "${COMMIT_MSG_FILE}.bak" "$COMMIT_MSG_FILE"
rm "${COMMIT_MSG_FILE}.bak"
exit 1
fi
rm "${COMMIT_MSG_FILE}.bak"
exit 0