MANAUS, Brazil -- Shortly after midnight on New Year’s Eve, hundreds of inmates watched from a Manaus prison yard as the sky lit up with fireworks, paid for by the gangs that dominate the jail system.

The revelry continued well into the next day, and inmates celebrated with their wives and girlfriends. But then the guards noticed something strange: The prisoners were asking their guests to go. “That is all for today, leave now,” guards heard prisoners say. The last family member left at 4:09 p.m. on New Year’s Day.

What happened next would go beyond any worst-case scenario imagined by guards or authorities, unleashing a brutality that would lay bare a failed prison system and a gruesome battle between gangs for influence in Latin America’s largest nation. The bloodshed would be the worst at any Brazilian prison in the past 25 years.

Get Breaking News Delivered to Your Inbox

The Associated Press gained exclusive access to the Complexo Penitenciario Anisio Jobim. What follows is based on the facility visit, footage from inmates on their mobile phones, forensics reports obtained by the AP and more than a dozen interviews with families of victims, authorities, lawyers, prison guards, judges, the warden and investigators.

“This was unprecedented,” said Carlos Procopio dos Reis, in charge of the medical forensics unit in Manaus. “I still dream that I am in a truck throwing heads for people to catch.”

_______________

Known by its Portuguese acronym of Compaj, the Manaus prison compound sprawls into the Amazon jungle. Families spend at least an hour on a prison bus line to get to the isolated penitentiary. Designed for 592 inmates, it held 1,224 on New Year’s Day.

Manaus, a violent and gritty northern city of 2 million people, is the jumping-off point to the Amazon and central to Northern Brazil’s growing drug trade. Drugs come here from Peru and Colombia through the Solimoes River and head to Belem, a port city by the Atlantic Ocean. Control of that waterway means access to the lucrative European market.

From prisons like Compaj around the nation, gang leaders oversee enormous drug businesses. For years, Brazil’s two most powerful gangs had a non-aggression pact. But that truce ruptured in October, for reasons experts say are still unclear, leading to riots in several prisons. At least 130 inmates have been killed nationwide since Jan. 1.

At the rough prison complex of Manaus, the New Year’s celebrations started with a rare moment of joy, as inmates danced to funk music with their wives and girlfriends inside the concrete 20-foot-tall walls. The next day, after everyone left, the tense moment came when prisoners needed to be locked up again.

But the lockup never happened. Instead, inmates linked to the Family of the North gang surrounded a prison guard and took him hostage, with a blade to his neck. Then they announced their larger intention: To get rid of all members of the rival First Command gang, also known as PCC.

“We will kick out of this prison every single PCC brain!” a prisoner from Family of the North yelled to the Compaj cameras.

That was among the last moments captured on film by the prison security cameras. Just after, inmates started to break the cameras, as they took over the prison. “It is all ours,” one of them shouted.

From then on, the only reports available came from witnesses and footage shot on mobile phones smuggled in to the prisoners.

The Family of the North moved quickly. Carrying knives, homemade shivs and even several pistols, prisoners led the first hostage into the atrium. There, they took another 14 guards and other staff hostage, including a cook and a nurse. Authorities say the inmates smuggled in their guns and blades through tunnels that enter a few areas of the prison and possibly holes in the wall.

While the main target was the rival gang, the attacking prisoners had a score to settle first with former policeman Moacir Jorge Pessoa da Costa, who had been jailed for killing drug dealers. At 4:17 p.m., the attackers told the others that Costa would be the first to be killed.

The inmates wanted to behead and dismember him, but they struggled to break the lock on his cell. So instead, reaching through the bars, they lit mattresses in his cell on fire and burned him alive. Rapists in the same wing would later meet a similar fate.

At 4:30 p.m., Family of the North prisoners began entering an area where many members of First Command were housed. The wing was known as “the safe.”

“Vai morrer!,” they shouted into a cell made for eight inmates but jammed with at least 27. “You’re going to die!”

_________

The battle between Family of the North and First Command is basically over drug routes in northern Brazil. The rift escalated last year when Family of the North from the Amazon teamed up with Comando Vermelho from Rio de Janeiro, Brazil’s second biggest gang. The evidence of that union is carved below the paint of some Compaj walls, where the acronyms FDN and CV can be seen.

On the other side of the war is the powerful First Command, based in Sao Paulo, Brazil’s richest and most organized gang. First Command was born out of the largest prison massacre in Brazil’s history, when military police killed at least 111 inmates during a 1992 rebellion. The gang has been expanding north, and now wants to take control of the Solimoes River from its rivals.

Family of the North local leaders -- nicknamed “Maraba,” ‘’Caroco,” ‘’Demetrio,” ‘’Garrote,” ‘’Rivellino” and “Maguila” -- headed the charge at Compaj. Authorities still don’t know whether the carnage was ordered from the outside by the gang’s top leaders, who are held in high-security federal prisons far from Manaus.

Crammed into their cells, many First Command prisoners had little room to run or means to fight back. Over the next 15 minutes, several were shot, stabbed or both. The screams of horror and pain filled the lockup.

Some First Command men managed to get to the roof of their cell block to hide. At least three jumped into the gutter, spending half a day drenched in feces and urine. A group of evangelical prisoners pleaded with the killers to stop, but they were locked in their cells.

No guards tried to intervene, as several had been taken hostage. But an elite police force surrounded the prison, in an attempt to keep hundreds of inmates from escaping through a hole in one wall.

Over the next 30 minutes, with police still outside, prisoners dragged dozens of bodies into the area dubbed Pavilion 3. Then Family of the North members, and other prisoners forced to take orders, began cutting. By the time they were done, 39 heads were lined up on the floor.

They also lopped off and piled up limbs, even from bodies that had been carbonized. They cut out 13 eyes and two hearts, and used them to terrorize others. One guard was forced to eat an eyeball. A transvestite prisoner was made to take bites of a heart, throwing up as she did so.

In the meantime, prisoners used their cellphones to capture photos and video of themselves, with a Family of the North flag in the background. At one point, a headless body appears. At another, an inmate holds up the hand of a dead person and waves to the camera, “He is saying bye.”

But Family of the North members wanted more. They wanted the whole prison, which housed about 200 more First Command members in other areas. If they succeeded, the massacre would get even worse.

____________

The first negotiations started at 6:30 p.m., when human rights activist and lawyer Epitacio Almeida, who knew most of the prisoners by name, talked with them through a radio device. But the talks were complicated after inmates shot a policeman in the right arm.

At 6:45 p.m., the first hostage was released for medical attention. By 9 p.m., a full battalion of riot police was firing on about 225 prisoners trying to escape, some by climbing the walls. It’s unclear how many died. Families and prison guards believe there are still bodies in the surrounding woods.

Amazonas state Public Security Secretary Sergio Fontes called in state Judge Luis Carlos Valois to mediate the crisis and gave him a bulletproof vest. At 10 p.m., the two men went past dozens of desperate family members outside the main gates to negotiate via radio.

As a sign of initial goodwill, inmates freed three hostages. Still, the standoff was far from over.

“You could cut the tension in the air with a knife,” said prison guard and union leader Rocinaldo Silva. “We feared for our colleagues inside, but we also worried about other prisons that could face the same problem after hearing the news.”

Fontes and Valois needed to meet with Family of the North leaders face-to-face. It took three hours, but at 1 a.m. “Maraba” and “Maguila” appeared with a list of demands.

In the meantime, the sickening stench of dozens of bodies took over the entire complex. Inmates asked for medical forensics agents to take away heads and limbs from the floor. The same carts inmates used to carry food were prepared to take remains.

At 3 a.m., after negotiations Fontes described as “surreal,” an agreement was reached. The prisoners bargained for regular visitation of family and women, time outside the cell and collection of bodies by medical forensics. In exchange, they would release the remaining 12 hostages and hand over weapons and cell phones.

When Valois told the rebellion leaders that he could not stop the entry of riot police or future transfers to other prisons, the inmates got upset. So the judge and secretary made it clear that either inmates put an immediate end to the rebellion or police would do it forcefully.

At about 7 a.m., the first of 39 heads arrived at the coroner’s office in downtown Manaus. In total, 57 prisoners were killed. Fearing the worst, dozens of families lined up in front of the building.

By 7:30 a.m., more than 15 hours after the rebellion began, the last hostages were released. Survivors who were hiding slowly reappeared.

___________

The massacre has left devastated families in its wake. Maria Angelina Muniz had two sons killed at Compaj: 20-year-old Antonio and 27-year-old Antony, who had been there just 10 days. Antonio was in jail for theft and Antony for drug trafficking, but neither son had been convicted.

Muniz said her family is sparing her from the details of how they died. The caskets were closed at the funeral.

“We knew they had a debt to society, they were paying,” Muniz said. “But now my life is destroyed because of this war.”

Seventeen inmates have been prosecuted and sent to tight-security federal prisons. Prison director Jose Carvalho da Silva, who is suspected of allowing weapons and mobiles into Compaj in exchange for money, has lost his job. Silva denies wrongdoing.

Former Amazonas Prison Secretary Pedro Florencio, a respected retired federal policeman, was also sacked because the massacre happened on his watch.

“To this day, I close my eyes and see parts of bodies of inmates everywhere,” Florencio said. “For me that New Year’s Day will never end.”

Days after the riot, smaller uprisings erupted in other prisons in the north. And the slaughter is likely to continue.

Speaking to the AP through a human rights activist, Family of the North inmates said a recent song described what they did and promised more to come. Prisoners said they sent the lyrics to a funk artist, who put the song on YouTube.

“The strength of Family of the North is building,” goes the song. “So have no doubt that the war has just begun.”