I don't think that once revolts begin in the colonies Spain is destined to lose them. It took a long time for the colonies to gain independence, and the revolutionaries had to fight armies and armies of Spanish loyalists to achieve victory. This is in OTL where Spain was notoriously incompetent, so I don't see how it is that hard to imagine if Spain has a better monarch then the Wars of Independence would be conducted more competently on the Spanish side, giving a greater chance to Spain of retaining her colonies.The ONLY real way I could see Spain avoiding getting caught up in the Napoleonic Wars would be to declare neutrality. OTL Spain tried fighting against the Revolutionary French and lost....then they allied with Napoleon and until he imposed his brother on them, they were willing to fight as allies because they had a common enemy in Britain. Once they started losing and began to revolt against the alliance THAT was when Nap put his brother Joe on the Spanish throne...and that was when the stirrings of revolt began in the Latin American colonies
Bottom line was that regardless of whether Spain fought with the French or against them, when they fought they lost. Spain would have to avoid being dragged into the Austrian and Polish Succession Wars, the Seven Years War and the American War of Independence in order to have the military might to be more victorious if they did get dragged into the Revolutionary/Napoleonic Wars. This is why their best bet would be to remain strictly neutral and focus on federalizing their colonial empire...maybe a Spanish version of the later British Commonwealth