  We describe from advanced first principles calculations the energetics of
oxygen doping and its relation to insulator-metal transitions in underdoped
YBa$_2$Cu$_3$O$_{6+x}$. We find a strong tendency of doping oxygens to order
into non-magnetic Cu$^{1+}$O$_x$ chains at any $x$. Ordering produces
one-dimensional metallic bands, while configurations with non-aligned oxygens
are insulating. The Cu$^{2+}$O$_2$ planes remain insulating and
antiferromagnetic up to a threshold between $x$=0.25 and 0.5, above which a
paramagnetic normal-metal state prevails. The in-plane antiferro-paramagnetic
competition depends on $x$, but only weakly on the ordering state of the
chains.
