To add to that last point, I always like to have a few quest-specific Deus Ex Machinas that I’ve got up my sleeve, in case I really badly miscalculated a battle.
Once I realize things are going badly for the PCs, I switch to playing as if they were supposed to lose this battle the whole time, so I can introduce this cool new thing. I try to make it seem like I planned it, but really, I’m just pulling a Deus Ex to save my party from my own dumb ass.