well ..... it's a different process for different people.
Yes, absolutely some people 'write' music as a process similar to an author writing a book.
But others do seem to have the music pop in fully formed.
Different strokes and all that
For me it's both.
Not sure how many folks (and how often) are able to get a complete song just "popping" into their head.

It might happen on occasion that everything forms within minutes...structure, melody, harmony, lyrics...but I think in most cases what pops into your head is the idea for a song. You can kinda hear how it will sound and what the overall vibe is going to be, but the rest comes with some effort.
I can get a half dozen song ideas in a matter of 30 minutes while strumming my guitar...but then it could take me days...weeks...months....to turn all those ideas into finished songs, and that part is usually a process that requires some focused effort, though each song is different, some form easily others take hard work.
A couple of weekends ago I had a couple of buddies over from back in my band days. One was the drummer, and the other our soundman. They wanted to mess around in the studio, so I spent about 10-15 minutes coming up with the basis of a song just so we could track the drums.
I then spent last weekend actually figuring it all out and turning it into a formal, structured song so I could move forward and start writing the lyrics and recording the other tracks.
As soon as we started laying down the drums to the rough scratch track, I already had the song working in my head, but I still needed to sit down and work it out more formally.