Although I guess it would make more sense to be looking at a chart of 2nd offences.
Someone locked up for insanity wouldn't be released while they are still a danger to the public. But anyone imprisoned for a violent crime might be released while still a very clear danger to society, even murderers and similar. Time limited sentences work that way.
I know of people on various medications for psychiatric reasons that have (against their doctor's recommendation) gone off their meds because they didn't like the side-effects. That might be fine (if unfortunate/difficult) for a mental illness that doesn't drive the sufferer to violence, but in the case where it does, how can you responsibly release someone if you don't have a mechanism to ensure they stay on their medication?
I think the actual 'enforcement' in the way you are thinking would be backed up with some kind of court ruling that they were required to take the medication, I'm not so sure how that angle would work.
They don't seem to work in that sense. There doesn't seem to have been a reduction in hospital use in that group.
English MH treatment is very different to the US though.
My understanding is that prisons are said to have four purposes: deterrence, incapacitation, retribution, and rehabilitation.
However, in the absence of having prisons a society would likely create prisons to protect the people of society. My conclusion is that prisons are meant to protect the populace with those other reasons being secondary based upon cultural mores.
How would prisons protect people? By deterring the people who might endanger them, by removing the capacity of people who do cause harm to cause more harm, by punishing those people, and by rehabilitating them into society.
The reasons aren't secondary or primary. They're different sides of the same coin, just stated from different perspectives: how to deal with the problem of crime vs. how to protect society from criminals.