Download the Android source from the official site for free: https://source.android.com/sou...
You might be thinking of the Play store and other Google apps, which as you say are not free. You can download and install them for free as a user, but if you want to ship them pre-installed on a device then there are licence agreements. Nothing in those agreements about having to launch a flagship phone or nonsense like that... Android is winning because it is available on everything from low cost low end devices to the very top tier hardware.
As for the costs, Cyanogen seems to prove that they can be pretty low. They support a lot of devices with very little funding to do so, partly because they are open source and rely on volunteers. Some companies pay them for support, which seems like a reasonable way to do long term updates.
You should never buy a phone from a carrier. Always get it unbranded and unlocked.