The narrative portions below are based on court documents in the case of the US v Khalil Abu Rayyan

(CNN) Every day was the same for Khalil Abu Rayyan, 21, a depressed pizza delivery man from Dearborn Heights, Michigan. Working for a pizzeria in Detroit, he'd drive late nights on desolate inner city streets, smoking pot hoping to keep boredom at bay. He carried a pistol to protect himself from robbers.

Rayyan wished he could meet a girl but his strict Muslim parents didn't allow him to date. He'd been troubled since the age of 12, when he was sent into counseling after telling his teacher he had a nightmare about bringing a gun to school and killing everyone in class. Tormented by bullies, he later got into fights that led to at least three suspensions. When he was 17, he started using marijuana.

Now, high school was over and Rayyan had a stable job at his dad's pizza shop but he still felt lonely, bitter and powerless, consumed with revenge fantasies. When he got home from work and logged onto his computer, he sought out shocking content in the darkest reaches of the Internet. He began watching ISIS videos in 2014.

He posted images of the terror group's atrocities on social media, a gruesome montage that included the beheadings of Coptic Christians, the burning death of a Jordanian pilot and men being thrown from high-rise rooftops for suspected homosexuality.

Rayyan felt insecure around the weightlifters at the gym, but online he portrayed himself as a menacing Islamist warrior. In one picture, he's cloaked in camouflage, holding a pistol and pointing his index finger skyward. It's a gesture that signals support for ISIS. It's a gesture that put the pizza man on the FBI's radar, according to a CNN review of ISIS prosecutions in the US.

Late one autumn day in 2015, Rayyan was at his lowest. He'd been pulled over by Detroit police for speeding and was arrested after the officer found a concealed revolver, four plastic bags of marijuana and sleeping pills in his 2001 Buick Century. Rayyan was released on bond but things looked bleak, with a seemingly endless series of court appearances on the horizon. Chronic gloom gave way to suicidal thoughts.

He tried to purchase a new pistol and was turned away because of his arrest. That same day, he went to a firing range and rented an AK-47-style rifle as well as an AR-15-style rifle. Background checks are not required for individuals renting firearms to use exclusively at gun ranges, according to the National Shooting Sports Foundation. Retailers may, however, use their discretion and decline to rent guns to individuals they suspect may be prohibited from owning firearms by law.

Two weeks later, Rayyan tweeted a picture of himself holding a rifle with a caption: "Sahwat hunting." In ISIS vernacular, a sahwat is a person who opposes the terror group. Sahwat refers to the Sunni tribesmen who fought alongside US-led coalition troops during the surge in Iraq.

First Ghaada, then Jannah

About a week after Rayyan posted the picture of the rifle, a woman named Ghaada contacted him on Twitter. She described herself as a Pakistani girl in Cleveland whose parents were pressuring her into an arranged marriage. Within days, Rayyan and Ghaada were making wedding plans, even though they had yet to meet in person. She was Rayyan's first girlfriend.

"While i was driving i started to cry because how happy i am to have you," Rayyan wrote.

"Don't cry my love. Please," Ghaada replied.

"Its tears of joy wallahi...I never felt this way before"

"I wish I could give you a great big hug!! You have no idea. I just I could jump through this phone right now"

"I need you"

"You have me from our first tweet"

Rayyan told Ghaada that he and his father planned to visit her in Cleveland so they could plan the wedding. And suddenly, Ghaada was gone. She stopped replying to his messages. She disappeared completely, and Rayyan didn't know why.

Two days after Ghaada vanished, Rayyan got a message from a young woman named Jannah. She said she was a 19-year-old Sunni Muslim .

Unlike Ghaada, Jannah expressed no interest in a conventional romantic relationship. She said she wanted to martyr herself for ISIS, an act of vengeance against the coalition troops and Shia militants in Syria and Iraq who had killed her husband and two of her cousins.

"Its like i knew you all my life," wrote Rayyan. "I will ask you (to marry me) but not now."

"Please don't rush me," wrote Jannah. "I'm depressed and very scared."

Jannah said she dreamed of committing a suicide attack with Rayyan as an expression of undying love.

"I'm not crazy Khalil," Jannah wrote. "It's my iman (faith). It's what I believe in. Jihad is my dream."

"Honestly you need to think about what you want," Rayyan replied. "I cant be in this game."

Conversation featured in court documents.

Rayyan wasn't that into the idea of violent jihad as an expression of spiritual love. He repeatedly told Jannah that she should rethink her plans and marry him instead. They could be happy. They could start a family.

"Dont do anything that will hurt u yourself or other people," Rayyan wrote. He later added, "Depression is real but don't let it run your life."

A violent dream and thoughts of suicide

As Rayyan tried to convince Jannah that martyrdom was a foolish choice, he confessed to her that he had struggled with violent thoughts himself. He said he wanted to kill the cop who had pulled him over for speeding. He claimed, falsely, that there was a sword in his car. He blustered that he once had contemplated shooting up a church near his pizza shop and he didn't intend to spare the women and children.

"Its one of the biggest [churches] in Detroit," Rayyan wrote. "i had it planned out ... i bought a bunch of bullets. I practiced a lot with [the gun]. I practiced reloading and unloading. But my dad searched my car one day and he found everything. He found the gun ... and bulletes (sic) and a mask i was going to wear. .. It wouldve been [a] blood bath but everything happens for a reason ... I dont no (sic) what the future leads. Maybe down the line i can try again."

Weeks of desperate messages to Jannah culminated with a foreboding phone conversation. Rayyan told her he had purchased a rope to hang himself.

"Only in like a minute or two, it'll be over," said Rayyan. "(My family) is going to be sad for a little while but they'll get over it."

Jannah responded that the only proper way for Muslims to kill themselves is in an act of violent jihad.

"Like I told you before ... when it's for the sake of Allah, when it's jihad, or when it's based on our [creed] or for a cause, that's the only time Allah allows it," said Jannah. "But not to put your life to waste, and just hang yourself like you say you want to do. That's not the right thing to do."

Later in the conversation, Rayyan said he did not want to hurt anybody else. He was interested in taking only his own life.

"If I did it to myself, it would be easier," said Rayyan. "I wouldn't get in trouble. I'm not trying to get arrested again."

A gun plea gets a terror sentence

Two days after the call, Rayyan got an unexpected visit. Federal agents arrested him for possession of a firearm by an unlawful user of a controlled substance. Rayyan didn't have a new pistol. He didn't have any guns. The firearm in question was the revolver that Detroit police had confiscated months earlier during the traffic stop.

Jannah, the woman who encouraged Rayyan to kill innocent people for Allah, was an undercover FBI employee. Rayyan's first love, Ghaada, was also a fictitious persona. In a court filing, prosecutors declined to reveal what agency or department may or may not have employed the individual who pretended to be Ghaada.

The government had engineered the romantic intrigue to bust Rayyan for ISIS support. The FBI spent nearly a year investigating him. Despite the investment of time and resources, the sting failed to yield any terrorism charges.

Rayyan could have been prosecuted for making a true threat, based on his comments to Jannah about shooting up the church and killing the traffic cop, but ultimately he was indicted solely for two gun offenses: firearm possession by a drug user and lying about his drug use to buy a pistol.

He pleaded guilty and was sentenced last April to five years in prison, a sentence almost three times longer than the advisory range for his offenses. The 33-page memorandum opinion centered on Rayyan's messages to Jannah, with the judge stating that concerns about public safety warranted a longer sentence.

"While it is true that [Rayyan] begged the UCE (undercover employee) not to hurt herself, he also discussed with her his plan to shoot up a church and assassinate a police officer," the judge wrote. "As the government aptly points out, [Rayyan] may claim he made the disturbing statements merely to 'impress' the UCE, but anyone who has been victimized by a terrorist attack would find his ideas far from impressive."

Rayyan's public defenders are fighting the sentence in the 6th US Circuit Court of Appeals. Their most recent filing was a reply brief on November 8. The government has yet to respond.

"Beyond vague representations of a desire to commit a terrorist act, made almost exclusively to an undercover agent posing as a love interest, Rayyan never took any action that could remotely be considered an 'initial step' toward the planning of an attack," his attorneys wrote in their appellant brief.

From ABSCAM to 9/11 to ISIS

The FBI has a decades-long history of undercover work to combat organized crime, drug trafficking and public corruption. In 1980, it famously busted several politicians who had taken bribes during an undercover operation called ABSCAM . Counterterrorism stings became a priority in 2001.

"In the wake of 9/11, it no longer is enough for law enforcement officers to solve crimes after their commission," FBI Academy instructor David J. Gottfried wrote in an article about undercover operations published in the FBI's Law Enforcement Bulletin . "Investigative activity that preempts crimes, particularly terrorism in a post-9/11 world, has become commonplace."

Over the last four years, ISIS has eclipsed al Qaeda in the top tier of domestic threats. Even as its self-declared caliphate crumbles, ISIS remains a dangerous group that uses social media to radicalize Americans and inspire attacks, according to the 2017 Worldwide Threat Assessment of the US Intelligence Community

The FBI often identifies American terror suspects by reviewing their activity online, according to a CNN review of ISIS arrests in the United States since 2014 . Undercover operations follow to determine whether the target of the probe is seriously planning a domestic attack or to join ISIS overseas.

About two-thirds of 114 ISIS arrests between 2014 and 2017 were the result of FBI stings, with paid informants and/or undercover agents posing as terrorist sympathizers and contacting suspects, according to CNN's review.

Informants and agents don't always play the role of passive listener. They may offer the suspect the opportunity to participate in a fictitious terror plot, replete with fake bombs and real guns, court records show. Fears of radicalized Americans have only intensified efforts at the FBI to identify radicals before they act.

"This approach of proactively identifying criminal activity in its infancy raises unique concerns," Gottfried wrote in the FBI's legal digest. "Can law enforcement officials exploit an individual's mere desire to kill tens of thousands of innocent people and even facilitate the commission of the crime right up until the last second, controlling the unfolding events to ensure that the perpetrators remain unaware they are dealing with undercover agents? Where is the line between an individual's thoughts and desires and criminal activity? The answer to these questions requires an understanding of an important legal principle -- entrapment."

Entrapment is the act of persuading an innocent person to commit a crime. If defense attorneys prove their client was entrapped, the court may dismiss the case. The entrapment defense is the main guardrail to protect the due-process rights of individuals targeted by undercover law enforcement.

There are two elements of the entrapment defense: inducement and a lack of predisposition, according to the Department of Justice . First, the defendant must convince the court that investigators induced him or her to break the law. Inducement can involve making emotional pleas or extraordinary promises "that would blind the ordinary person to his legal duties." Secondly, and more importantly, the defendant must demonstrate a lack of criminal predisposition. Prosecutors fight entrapment claims by probing the defendant's past and reflecting on his or her character , presenting evidence of earlier crimes that might not otherwise be admissible.

No one has successfully challenged a federal terror charge by proving entrapment, according to CNN's review of ISIS cases and a 2014 Human Rights Watch study of post-9/11 terror prosecutions

The outrageous government conduct defense is another constitutional guardrail. A court can overturn a conviction if the conduct of the undercover officers or informants is so outrageous it is "shocking to the universal sense of justice."

Defense attorneys rarely prevail when they file motions to dismiss cases on the grounds of outrageous misconduct, according to a 2015 study by the Center on Media and Justice at John Jay College of Criminal Justice in New York . Examining cases in an 18-month time window, researchers found 126 motions to dismiss cases on the basis of government misconduct. Just three of the 126 motions led to dismissals. Two cases were dismissed because undercover police officers had had sexual contact with women they were investigating for prostitution at massage parlors. The third case was tossed because a prosecutor had added a false confession to the transcript of a police interrogation.

Rayyan's sentence

Rayyan's attorneys raised the issue of entrapment in a brief to support a motion for bond. After reviewing a sampling of the messages between Rayyan and the two fictitious women, his lawyers concluded that the government had engaged in a "disturbingly crafted seduction and manipulation of Rayyan through the inducement of love. Most investigative agencies avoid proffering romantic inducement in a sting operation for fear of creating a substantial entrapment claim, after all, 'love' is universally desired."

Prosecutors argued that Rayyan wasn't entrapped because he had bought a gun and lied about his drug use to obtain the weapon long before the undercover agents entered the picture. The government followed up by asking the court to preclude the entrapment defense. The point was moot, however, as Rayyan pleaded guilty rather than go to trial.

Guilty pleas are good for the government because they conserve court resources. In exchange, judges can make sentencing concessions based on the individual's acceptance of responsibility, according to the American Bar Association

Even though Rayyan pleaded guilty, however, his sentence was not reduced. Though the maximum sentencing for each count was 10 years, the agreed guidelines for his gun violations called for a total of 15 to 21 months in prison. He got 60 months. It was the middle ground between prosecutors' suggested sentence of 96 months and the defense's 15-month proposal.

The defense cautioned that a lengthy prison sentence could cause Rayyan's mental health to deteriorate, leading him right back into the ISIS vortex.

The judge acknowledged that prison is not an ideal therapeutic environment for individuals struggling with addiction, suicidal thoughts and violent revenge fantasies. He wrote, however, that prison would provide Rayyan with "needed educational or vocational training, medical care, or other correctional treatment in the most effective manner."

Rayyan's attorneys filed an appeal, objecting to the district court's reliance on uncharged conduct to justify a longer prison term. If the government lacked evidence to indict him for ISIS support, his statements to Jannah and online activity shouldn't have factored into his sentencing, his lawyers argued.

Prosecutors responded with a reference to Al Capone, arguing that one of the 20th century's most famous criminal trials hinged on uncharged conduct. They said Rayyan's messages about wanting to shoot up the church must be addressed.

"Sentencing Rayyan based solely on his gun possession -- without considering his terrorism plans -- would have left 'the same feeling of true-but-inadequate as the conclusion that Al Capone did not accurately report his income," the prosecutors wrote, referring to the fact that the murderous mobster was ultimately convicted of tax evasion.

Rayyan's attorneys countered that the government didn't have evidence that Rayyan was planning anything.

"To allow the government to effectively back-door a terrorism case where it did not even have sufficient evidence to indict on such charges is an affront to our very notion of justice and due process," Rayyan's attorneys concluded.

While the prosecution and defense have traded motions and briefs about the complexities of the case, Rayyan's been penning apologies to his family. In a letter to his mother, he wrote, "This whole situation was because I wanted to get married."

During one of Rayyan's final exchanges with the person posing as Ghaada, she cryptically warned him that he might be under government surveillance, according to court records.

"You have to be careful Khalil. It sounds like you are being watched," Ghaada wrote.

An apparently smitten Rayyan replied, "I think they are looking for people that want to attack them or go to Syria."

"I don't want to do either of that," Rayyan wrote. "I just want my baby."