I needed a lawyer for a misdemeanor charge (cop was having a bad day, the other cops that arrived on the scene seemed like they would have let me off with a warning but it was not their call). I was certainly guilty by the letter of the law and had no defense but the lawyer I was referred to from a friend of a friend negotiated with the prosecution and I plead guilty to a civil ordinance violation for disturbing the peace (basically a traffic ticket). He was able to do that because he knew what to bargain for based off of similar cases in my state.
However, if it doesn’t get worked out pre-trial, that negotiation process still happens in the court room. When I met my lawyer, he mentioned a recent case he handled where the defendant had committed murder. There was no question that he did it, but the lawyer was proud that he was able to convince the court that his defendant was not of sound mind, which was the difference between going untreated and spending twenty-to-life in a state prison or spending that time getting treatment in a mental ward. While the latter isn’t exactly a cushy place to be, it is certainly better than being mentally unstable in gen pop.