The reactions of the low-lying metastable states of atomic phosphorus, P(2D) and P(2P), with H2O and H2 were studied by the pulsed laser photolysis at 248 nm of PCl3, combined with laser induced fluorescence detection of P(2D), P(2P) and PO. Rate coefficients between 291 and 740 K were measured, along with a yield for the production of PO from P(2D or 2P) + H2O of (35 ± 15)%. H2 reacts with both excited P states relatively efficiently; physical (i.e. collisional) quenching, rather than chemical reaction to produced PH + H, is shown to be the more likely pathway. A comprehensive phosphorus chemistry network is then developed using a combination of electronic structure theory calculations and a Master Equation treatment of reactions taking place over complex potential energy surfaces. The resulting model shows that at the high temperatures within two stellar radii of a MIRA variable AGB star in oxygen-rich conditions, collisional excitation of ground-state P(4S) to P(2D), followed by reaction with H2O, is a significant pathway for producing PO (in addition to the reaction between P(4S) and OH). The model also demonstrates that the PN fractional abundance in a steady (non-pulsating) outflow is under-predicted by about 2 orders of magnitude. However, under shocked conditions where sufficient thermal dissociation of N2 occurs at temperatures above 4000 K, the resulting N atoms convert a substantial fraction of PO to PN.