On the origin of molecular oxygen in comets