It depends and it definitely varies based on how the team is working.
But majority will opt for the proper guidelines..
1) Are the songs recorded Pre-shoot by hearing the story / script ?
Yes. The screenplay will be narrated during pre-production to the music composer and based on that he/she will compose the music. Similarly the bgm, the tone of the film will be explained earlier which will clarify the music composer [Sometimes background score is given by different person] and they will compose accordingly.
Adding on the special situations where songs will be added later. This happens when the director/producer or as it only happens in India, when an actor demands for a song to be added and gives particular inputs. To give an example, Varun Dhawan demanded a dance number where he can dance like Govinda and a song was composed to suit his demand. The song was "Aashiq Surrender Hua".
Not always this happens, as music directors will have their music bank or song bank where they'll have their tunes stored. They'll sell them. Salman Khan has purchased plenty of such tunes/songs from Sajid-Wajid, Rahat Fateh Ali Khan which he can use whenever he wants. Habibi Ke Nain from Dabangg 3 was one such song.
2) Or it's composed post shooting / post film ?
It is always composed pre-shooting. Only in rare cases which I've mentioned above, it will be done while shooting. Post film, no song composition will happen.
So to you further queries, while finalising the screenplay itself they will make space for the songs. If a director loves a song too much, then he may insist on re-writing a scene just to accomodate that song. As far as your question on K3G goes, that was organic. The song was not an after thought. It was part of the script.
Speaking of part of the script, the best way to learn the difference is with Sooraj Barjatya films. There are no "Dream songs" or "Song break" in his films. All of it is imbibed into the script. And if you want to check out films that have specific "song breaks" then you can check out any recent masala fares.