FORT BRAGG, N.C. — At his first major court hearing two years ago, it seemed that Sgt. Bowe Bergdahl had caught a break: the Pentagon’s hostage debriefer, Terrence Russell, testified that the sergeant had “done the best job he could do” during the five years he was held by the Taliban, resisting his captors and attempting escape despite suffering the worst prisoner-of-war abuse since Vietnam.

The military’s own investigator rejected widespread claims that soldiers had died while searching for the sergeant, and recommended against punishing him with any jail time.

But Sergeant Bergdahl is now facing up to life in prison. A week ago, he appeared here at Fort Bragg and essentially capitulated, pleading guilty to all charges. On Monday, he returned to the courtroom in a final attempt to have the case dismissed. His sentencing hearing is set to begin on Wednesday.

How did his legal fortunes turn so drastically? Many things have been at play. The sergeant’s own statements to investigators went a long way toward proving the charges. The defense team lost on some crucial motions, including one in which the judge ruled that service members had been wounded during the search. And politics have dogged the case, with defense lawyers arguing that their client cannot get a fair trial because Donald J. Trump repeatedly called Sergeant Bergdahl a traitor during the presidential election last year.

By taking full responsibility for the actions he is accused of, legal experts say, Sergeant Bergdahl is probably making a last-ditch bid for mercy.

The sergeant was released in May 2014, when President Barack Obama traded five Taliban detainees for him. Mr. Obama embraced Sergeant Bergdahl’s parents in the Rose Garden, and his national security adviser, Susan E. Rice, said the sergeant had served with “honor and distinction.”

That set off a political furor that ultimately became a presidential campaign issue. Mr. Trump made calls of “dirty rotten traitor” a staple of his speeches, and said the sergeant should be executed.

“Bing, bong!” Mr. Trump told his supporters, mimicking the sound of a rifle shot as he pantomimed a firing squad.

The judge in the case, Col. Jeffery R. Nance of the Army, called Mr. Trump’s comments “disturbing,” but rejected a defense motion to dismiss the case on the ground that a fair trial was impossible. On Monday, Colonel Nance heard another, similar motion after President Trump appeared to endorse his campaign-trail sentiments.

“They’re setting up sentencing, so I’m not going to comment on him,” Mr. Trump said when asked about the case. “But I think people have heard my comments in the past.”

The judge is expected to rule on the new motion before Wednesday.

Fury over the Bergdahl affair began well before the presidential campaign. Republicans on Capitol Hill, enraged by the release of the Taliban detainees, peppered the Army with questions about the Bergdahl investigation.

Before the investigation was complete, officials at Army headquarters made a significant decision. Though the sergeant had been assigned to a base in San Antonio, they ordered that any proceedings against him be handled at a higher level. They eventually chose Forces Command at Fort Bragg, six states away.

Forces Command is the largest provider of conventional troops in the military, and Fort Bragg is home to some of the Army’s most elite forces. The San Antonio base, by contrast, is more focused on medical and other support functions.

“The Army knew that Forces Command consists of a more combat-hardened culture and community, versus the support community of the command at San Antonio,” said Rachel VanLandingham, a professor at Southwestern Law School in Los Angeles and a retired Air Force lawyer. She added, “They chose it to exploit the combat culture of Fort Bragg at trial,” which she said would have been less sympathetic to Sergeant Bergdahl.

“There just seemed to be a lot of manipulation in this case, all resulting from the political pressure on the Army,” she said.

A spokeswoman for the Army said that the decision was made to place a more senior commander in charge, while allowing the commander in San Antonio “to focus solely on his responsibility for Bergdahl’s security, care and day-to-day activities.”

Documents from the Army’s inquiry indicate that the lead investigator, Maj. Gen. Kenneth Dahl, believed that the most serious charge Sergeant Bergdahl should face was desertion, carrying a sentence of up to five years. But Forces Command, under the command of Gen. Mark Milley, added a much more serious accusation: that Bergdahl had endangered the troops sent to search for him. The rarely used charge, formally known as misbehavior before the enemy, carries up to life in prison. Sergeant Bergdahl pleaded guilty to both charges.

General Dahl did not publicly reveal his investigative findings until September 2015, six months after the charges were filed. Sergeant Bergdahl had left his outpost with the misguided intention of hiking to a larger base so he could report concerns about problems in his unit, General Dahl said. The sergeant was delusional and naïve, but had never intended to defect to the Taliban.

In a victory for the defense, the preliminary hearing officer, Lt. Col. Mark Visger, said that while there was ample evidence to proceed to a court-martial on both charges, he endorsed General Dahl’s recommendation against jail time, saying the sergeant should be tried not at a general court-martial but before a lower tribunal where he would face only up to a year’s confinement.

There was also the question of Sergeant Bergdahl’s mental state. An Army medical board concluded that he had been suffering from a severe psychological disorder when he walked off his base. Two years before joining the Army, Sergeant Bergdahl had washed out of Coast Guard basic training for mental health and other reasons, and a Coast Guard physician said he should be cleared by a psychiatrist before being allowed to re-enlist in the military. But the Army apparently failed to obtain the clearance, Colonel Visger wrote.

“The fact that Sergeant Bergdahl had mental health problems was known within the U.S. military, and events may have transpired differently had concerns about Sergeant Bergdahl’s mental health been properly followed up,” he wrote.

The defense opted not to pursue a mental illness defense, but can still present evidence about his mental state during the sentencing phase of the trial in hopes of greater leniency.

Colonel Visger’s recommendation drew an immediate reaction. Senator John McCain of Arizona, the Republican chairman of the Armed Services Committee, which would sign off on any future promotions for the general overseeing the case, said publicly that Sergeant Bergdahl was “clearly a deserter,” and warned that the committee would hold hearings on the case if there was no punishment.

The Army, alarmed by the appearance of political interference, asked Senator McCain’s committee to issue a “curative statement.” It did not.

By this point, Gen. Robert Abrams had replaced General Milley and taken over command of the case. He ordered a general court-martial. General Abrams later testified that Senator McCain’s comments were “inappropriate” but had not influenced his decision.

Over the next 18 months the prosecution and defense argued a critical question: the admissibility of evidence of troops wounded during the search. The main reason Colonel Visger recommended leniency, he wrote, was lack of evidence that troops had been harmed. But after hearing the prosecution’s arguments, the judge ruled that evidence of injuries could be used during sentencing.

One of the wounded, Master Sgt. Mark Allen, a Georgia guardsman who was shot in the head during a firefight a little more than a week after Sergeant Bergdahl disappeared, now uses a wheelchair and is unable to speak or care for himself. Another, Senior Chief Petty Officer Jimmy Hatch, a member of a Navy SEAL unit, suffered a severe leg wound that required dozens of surgical procedures and an agonizing recovery.

According to some legal experts, the question was never so much whether Sergeant Bergdahl was guilty but how severely he would be punished, a decision now in the judge’s hands. Typically, a guilty plea is accompanied by an agreement to cap the maximum sentence, but Sergeant Bergdahl obtained no such deal. Instead, his plea may have been calculated to win points with Colonel Nance.

“Accepting the risk of the maximum penalty with a naked plea is very unusual,” said Geoffrey Corn, a former Army lawyer and lieutenant colonel who is now a professor at South Texas College of Law in Houston, “But it is the best type of plea to show a defendant is serious about taking responsibility for their misconduct.”