I am not sure we are seeing the same behavior. For the unit being carried, (1) loading takes all movement points but (2) you can load if you have no movement points. Unloading is only allowed if (3) the unit being carried has movement points left. It does not matter whether the transport has movement points left; the unit can still unload.
There is one consequence you may have overlooked, and there is one button which appears when it should not; but the above behavior is what I designed and how it works in 1.5.4, 1.5.5, and 1.6
Hmmm. Ok. It sounds like have misinterpreted. It sounds like the system is working as you designed it.
Then that would suggest that it *is* an AI issue that they aren't unloading transports immediately once the transport is next to the enemy city, but also suggests that an AI that unloaded them and reloaded them *every* turn when they were over land would fail too, because if they load them up at the start of the turn then they will be unable to unload them once the transport moved.
We may need to decide then which is worse; AI that is very vulnerable to having their transports destroyed while the troops are still cargo, or humans exploiting transports.
My ideal design would be:
i) Units can always be unloaded or loaded into transports, no matter whether they have any movement points left.
ii) Unloading from a transports uses up all the movement points left that a unit has *if* and only if it has any left.
That way, you don't have the exploits where a human player can unload a unit, attack with that unit (or unload a worker and have it spend a turn building an improvement), then reload the unit and move away, but you also allow land units to defend the transports while they are over land (by having the AI unload and reload them every turn).
So I think your code is correct, but your design is not optimal.