How to switch between usb host and slave mode on a micro usb programatically?
Just like the chip in your phone, many (if not even most) of microcontrollers with USB interface can be programmed to be a host or a device, and could hypothetically even switch these roles. Exactly as your phone does!

A USB bus can't have multiple masters, so the "optional" goal of letting the phone be device to a PC and host to a keyboard is impossible to achieve on the same bus.

You really just want a bus switch compatible with USB signalling levels and speeds.

Since USB is such a large market, these things are produced by many IC manufacturers, for example Texas Instruments has a whole range of USB2 and USB3 switches; take the TS3USB30E as an example of a USB2 switch. Octopart tells me it can be had for little more than 1€. 



So, you'd just wire up your connector going to your phone to the D+ / D- lines,
the one going to your PC to the D1+ and D1- lines, and the one going to your keyboard to the D2+ / D2- lines.

To let the phone know that it's supposed to be in host mode, you will have to pull down its "ID pin" to ground (that's the fifth pin in a micro-USB connector). You can do that by means of yet another simple analog make-or-break switch (example).