let's say given the supply voltage is 12v, I want it optimised to run
at a constant RPM of 4000 and drawing no more than 0.5 amps.
how do I calculate the wire size and number of turns?
Without more information it is impossible to say.
'Iron' loss (magnetic and friction) increases as speed increases, but 'copper' loss (winding resistance x current2) increases as more current is drawn. At idle (no-load, minimum current draw) efficiency is zero. At maximum power output the winding resistance absorbs about half the input power and efficiency is 50% or less. Peak efficiency occurs somewhere between those two points, when iron loss equals copper loss.
Magnetic losses are determined by the physical design and construction of the magnetic path (stator shape, core material, air gaps etc.) Winding resistance is determined by wire diameter and length which is dependent on the space available, but the length required to get a particular rpm is determined by motor dimensions, winding pattern, magnet placement and strength. A large motor needs less turns of thicker wire than a small motor of the same design, and a motor with strong magnets need less turns than one with weak magnets or a larger airgap (but stronger magnets increase iron loss, so...).
If you have a motor that runs on a different voltage than you want, you can rewind it to run on a different voltage by changing the number of turns in proportion, eg. if it does 4000rpm on 6V now then double the number of turns to get 4000rpm at 12V. But that takes up twice as much space so you must reduce the diameter by 1.4 (to get half the area per wire).
However, rewinding will probably not produce maximum efficiency unless you are very lucky. For a given motor, peak efficiency occurs at a particular rpm and power no matter what voltage it is wound for. For example if your motor currently does 4000rpm at 1A on 6V with 70% efficiency, if you rewind it to do 4000rpm at 0.5A on 12V it will still get 70% efficiency.
If you rewind for lower rpm it will have higher resistance and copper loss, whereas if you rewind for higher rpm the magnetic loss will increase. If it is too small then copper loss will dominate due to the smaller amount of copper, but if it is too large then iron loss will dominate because the larger core has higher magnetic loss. So when you rewind it for different rpm the efficiency could get better or worse, depending on the particular motor and where you are operating it on the efficiency curve.