Arizona has a good solution. A man killed his wife and claimed insanity. He was acquitted and sent to a mental institution. Two months later, he was deemed no longer insane and released. Never spent a day in prison.
The law was changed. Now you can be found guilty but insane. You then get sent to a mental institution. If eventually, you are no longer insane, you finish your sentence in a prison.