The problem where it idles poorly, then the battery is disconnected, at which point it starts to idle good, but over time it returns to the poor idle state is a key finding and could indicate a bad sensor somewhere. When you disconnect the battery, the computer forgets everything it has learned about the sensor readings, so it reverts to pre-stored parameters from when the car was new. Over time it reads the sensors and re-learns the optimum way to set the engine parameters. It sounds like somehow this relearning is fouling things up. The most simple way for that to happen is if one or more of the sensors are reporting false or inconsistent data. That confuses the computer and it can’t figure out how to set the parameters so the engine runs correctly.
So which sensor? First thing is to have all the diagnostic codes read, that might provide a clue. Absent code data, with the symptom I’d tend to suspect the MAF sensor, but it could be any of the major sensors among them the engine coolant temp sensor, the MAP (if it has one), pre- and post-cat o2 sensors, etc. One thing to ask for that might help diagnose this problem in addition to the diagnostic codes is a reading on the fuel trim. That indicates how much the computer has to modify the engine parameters from what it thinks it should be to get the fuel/air mixture correct.