As far as I know, if you commit some crime and are found mentally ill, you do not go to jail. Instead you go to a mental hospital, where you are treated until you are fine. Then you are free. Hence the whole "pleading insanity" option in various movies/tv shows. It would not make sense to stay 3 years in a hospital and then also get the full sentence.
This being said, lucidity would not also bring his arrest.
Now, as to the whole problem, to my mind he is cured at the end, but keeps pretending in order to be lobotomized. He realizes that he cannot live knowing the truth, preferring this solution instead. The doctor's nod means(to my mind) that he gives the permission for lobotomy. It is a sad look, so it cannot mean that he tells them that it worked.
Here is a similar question and the accepted answer provides more details.
There still remains an unanswered question(nobody has asked it, but I believe that there is also no proper answer to it): Does the doctor understand what Teddy means? More precise, is aware that Teddy is cured and approves the lobotomy as a favor for him(the gift of mercy) or is he simply fooled by Teddy's acting and does not understand the meaning of the last sentence?