Songs written for movies by well-known artists are quite common, with examples such as Hozier for Tarzan, Ellie Goulding for 50 Shades of Grey and Pink for Charlie's Angels, sometimes going as far as to reference the film within the song. These songs are then often released by the artist as a single, or part of an album.
I would assume this means that the rights to the song are kept by the original artist or writer, allowing them to make money from the song in their own right, and the property is leased by the movie production to be included within the movie.
My question is: how does this process usually work?
Would movie producers approach an artist who makes a particular style or genre of music that they are trying to include in the movie, and ask the artist to write a song to fit that, or would they approach a number of artists and ask for songs, then decide the best choice?
Would they be asked close to the beginning of production during the creative process in order to let the song influence the movie, or is it closer to the end of production and the song is then written to a specification to fit the feel of the movie?
Particularly considering that the songs are usually later released by the artist (or sometimes before the release of the movie), the song itself needs to be of a good quality and follow the structure of an actual song. Do the movie productions simply ask for a melody or hook that they can sample for the movie's score, which the artist then builds into a full song, or is the song written and the movie chooses the best parts from it?
Note: I'm specifically asking about songs that are used within the movie itself as opposed to during the credits, such as the majority of James Bond themes. Also, not songs that already exist and are included in a film years later, just songs that are created specifically for the purpose of being included in a movie.
Also, if any of my assumptions are incorrect, I would be happy to change them, or if any of the sub-questions aren't answerable because there is no definitive answer I will remove them.