In Deuteronomy 31:1-2 is states:
"And you return to the Lord your God, and you and your children heed His command with all your heart and soul, just as I enjoin upon you this day, then the Lord your God will restore your fortunes and take you back in love. He will bring you together again from all the peoples where the Lord your God has scattered you."
This would seem to imply that the final ingathering of exiles will only come as a result of returning to Torah observance. Yet the Talmud Sanhedrin 98a says unequivocally that the messiah can come whether we are worthy or not:
"And Rabbi Yoḥanan says: The son of David will come only in a generation that is entirely innocent, or entirely guilty, in which case there will be no alternative to redemption"
How to reconcile?