Chief executive Tim Cook sought new factory locales outside China, a prescient move that along with a new $100 billion U.S. investment will shield the company—for now.