FORT BRAGG, N.C. — In an unexpected and emotional statement, Army Sgt. Bowe Bergdahl apologized in court Monday to all the military personnel who were wounded searching for him and described the daily nightmares and flashbacks he still endures over his five years in captivity by Taliban allies.

Bergdahl was the first witness in what’s expected to be the defense’s multiday presentation to the judge who will decide his punishment for endangering comrades by walking off his post in Afghanistan in 2009. He spoke for two hours, giving a wide-ranging description of his years in brutal captivity and what challenges he still faces.

“I would like everyone who searched for me to know it was never my intention for anyone to be hurt, and I never expected that to happen,” he said, choking up at times. “My words alone can’t take away their pain.”

Bergdahl faces a maximum of life in prison after pleading guilty to desertion and misbehavior before the enemy.

His appearance on the witness stand, which the defense hadn’t publicly made known in advance, served as a dramatic counterpoint to several days of emotionally wrenching testimony by several service members who were seriously wounded during a massive search effort. He described the brutal conditions he faced, including beatings with copper wire and unending bouts of gastrointestinal problems brought on by squalid conditions. He was kept in a cage for four out of the five years after several escape attempts, and his muscles atrophied to the point he could barely stand or walk.

Asked by a defense attorney what the worst part of captivity was, he responded that it wasn’t the beatings.

“The worst was the constant, just the constant deterioration of everything. The constant pain from my body falling apart. The constant screams from my mind,” he said, haltingly. “It was the years of waiting to see whether or not the next time someone opens the door if that would be the person coming to execute you.”

Bergdahl said he still has nightmares that make it hard to sleep more than five hours. He checks his door at least three times to make sure it’s secure each night and sleeps with a flashlight nearby.

He wakes up sometimes not remembering that he’s back in the U.S., he said, and has daytime flashbacks to captivity arising from unpredictable triggers.

“It could be anything: A smell, perfume, damp earth, garbage,” he said.

The 31-year-old soldier from Hailey, Idaho, was brought home by President Obama in 2014 in a swap for five Taliban prisoners at Guantanamo Bay.

Because Bergdahl’s words in court were an unsworn statement, prosecutors won’t be given the chance to cross-examine him.

His dramatic words came after an eventful morning in which the judge ruled that Donald Trump’s scathing criticism of Bergdahl won’t prevent the soldier from receiving a fair sentence.

Then-Republican nominee Trump called Bergdahl a traitor and suggested that he be thrown from a plane without a parachute.