​Now he’s officially off the rails.

​After years of brushing off deals​ offered by prosecutors​, New York​ City​’s infamous ​serial ​transit ​bandit opted Monday to cop a​ plea that will indefinitely​ ​land him in a psychiatric facility.

Darius McCollum, who has Asperger​’s​ syndrome​ and has been unable to resist taking over buses and trains since he was a teen​, agreed to a deal that would find him not responsible by reason of mental disease or defect​ ​for​ his latest transit-jacking — allegedly commandeer​ing a Greyhound bus in Nov​ember ​2015 from ​the ​Port Authority​ terminal​.

The 52-year-old made the decision the same day he was slotted to head to trial​.​

“I went home that night, it was raining,” McCollum told the court, as he recalled his drive after swiping the bus. “I parked at my house, went home and slept.”

As a three-time felon​ ​–​ ​all for ​bus- and train-related ​thefts ​–​ ​he would have faced ​as much as life behind bars if convicted at trial.

The ​mass-transit buff recounted how, the morning after he nabbed the Greyhound coach, he drove it back into Manhattan from Queens, then into Pennsylvania, then back to Queens and into Brooklyn​ ​–​ ​where he was ​arrested.

As part of Monday’s deal, doctors will determine if McCollum poses a violent risk to society, which will affect the terms of his commitment.

McCollum had previously passed up three other deals that would have landed him in prison for ​five to 10 years.

“We are not agreeing he is dangerous,” defense attorney Sally Butler told reporters following Monday’s appearance. “He is very happy he is going to be treated.”

If he’s not found to pose a risk to society, McCollum will be sent to a ​non-​secure hospital where he’ll have privileges and be allowed to see his mother, Butler said.

“He’ll have services like he’s never had before. Some diagnosis and treatment,” the lawyer added.

“It took us 2​ 1/2 years to get them to believe he doesn’t belong in jail,” said Butler, grinning. “I’m happy.”

The ​wannabe Ralph Kramden has been busted over 30 times for variously co-opting trains and buses around the city, and was first arrested at age 15 when the conductor of an E train left him alone at the helm​ ​–​ ​and the teen drove from 34th Street to the World Trade Center.

​The Queens man was diagnosed with Asperger’s and Obsessive Compulsive Disorder in his 30s, according to Butler.

McCollum’s decision to take the deal comes a less than a week after Brooklyn prosecutor Janet Gleeson accused Butler of talking the transit bandit out of taking the deals.

She’s denied those claims, but a third attorney was brought in Wednesday to counsel McCollum regarding the pleas.

A documentary about McCollum, ​”​Off The Rails,​”​ was released last year. A Hollywood film is ​now in​ the works.

As Butler left court, a beaming McCollum passed her a note that said​,​ “​T​hey finally got it right.”