In an early episode of "The Office," Michael Scott has a client meeting at a local Chili's, accompanied by his very skeptical boss from corporate (and unrequited crush) Jan. Jan understandably views Michael in the same way we do after a dozen installments of the young NBC series: as a buffoon who is painfully, erroneously convinced of his gifts as a boss, as a salesman and, especially, as a comedian. The early part of the meeting couldn't seem to be going worse, with Michael continually disrupting every one of Jan's attempts to talk about making what could potentially be a huge sale, telling off-color jokes, playing Truth or Dare and pressing Jan for embarrassing details about the end of her marriage. It's another obvious Michael Scott disaster in the making.

And then to our amazement, and to Jan's, Michael pulls it off. It turns out Michael understood the client better than Jan did and was expertly bonding with him long before he first mentioned business. He makes the impossible sale, and even winds up spending the night with an impressed (and very drunk) Jan.

That, in a nutshell, is the American version of "The Office," which ends tonight at 9. By almost any reasonable argument, it had no business working, creatively or commercially. It was messy. It was problematic. At times it could be mortifying. And all the odds were stacked against it from the start. Yet here we sit, hours away from the show ending its run after nine seasons, 200-odd episodes, and a long stretch of critical adoration (even if these last few seasons have been pretty rough). And like Jan watching Michael close that sale, it's not hard to sit back, marvel and ask, simply,

How the hell did that happen?

Consider the many obstacles placed against the series at the start:

* It was a remake of a British comedy at NBC, only a season after NBC had premiered one of the very worst Britcom translations of all time in its short-lived version of "Coupling."

* It was not only a Brit remake, but a remake of a very specific, acidic comedy, featuring a deliberately off-putting main character, in a formula so difficult to pull off that its creators, Ricky Gervais and Stephen Merchant, only produced 12 episodes and a Christmas special before walking away.

* The first American "Office" episode was a note-for-note remake of the British premiere, and it was terrible; what had seemed ridiculous and cheeky coming out of Gervais' mouth instead seemed menacing when American star Steve Carell said it.

* Greg Daniels, the American writer tasked with adapting the series, admittedly didn't have a firm grasp for how to write the Michael Scott character until after the first season ended, and he saw Carell in "The 40-Year-Old Virgin." And even afterwards, Michael went through some pretty drastic personality swings throughout Carell's run on the series. Some weeks, he seemed to have Asperger's; in others, he was a bumbling but astute guy. Some weeks, he was well-meaning but oblivious; in others, he was the world's most petulant, destructive overgrown little boy.

* Though Michael was the main character, and usually the driver of both the plot and the jokes, the series' hero and heroine were his bored underlings Jim and Pam, whose slow-burning love story became the hook that grabbed many viewers. But by the design of the series, Jim and Pam inevitably had to take a back seat to the antics of broader characters like Michael and his obnoxious lackey Dwight. 

* While the show could be incredibly sweet, particularly in material involving Jim and Pam, it also had the capability — and desire — to be so uncomfortable that the only safe way to watch it sometimes was from behind your catch, through your fingers while wearing an eyepatch and one earplug.

How did this possibly work? How did a show about an oblivious clod who had to buy himself a World's Greatest Boss mug — because none of his actual employees would ever think to do it — become a hit? How did a show with so many combustible, seemingly mismatched elements, become one of the best, most influential comedies of the 21st century?

The answer begins with two words: Greg Daniels.

Even now, as "The Office" prepares to go off the air, it feels like Daniels hasn't quite gotten his due as one of the great comedy minds in the business. After a stint on "Saturday Night Live," writing alongside his old college classmate Conan O'Brien, Daniels wound up on staff at "The Simpsons," where he wrote many of the best episodes of the show's strongest creative period, including "Homer and Apu" (featuring the ageless song "Who Needs the Kwik-E-Mart?") and "Homer Badman" (which turned out to be Gervais' favorite "Simpsons" episode when the two men met to discuss the adaptation). He then co-created "King of the Hill," which managed to be one of the most human comedies on television despite being animated. And after making "The Office" into a hit, he would co-create (with longtime "Office" writer Mike Schur) "Parks and Recreation," which would, like its predecessor, grow in time into a classic.

Daniels is a smart, gifted writer, and one who can adapt when things aren't working. The pilot's bad because Carell is not Gervais, and therefore Michael Scott shouldn't have been David Brent — even though both men shared common attributes (and hit it off famously when Gervais cameo'ed late in Carell's run) — and even before "The 40-Year-Old Virgin" was released (which helped the writers, and also drove viewers to find the series and its suddenly popular star), Daniels and his team began adapting the show to fit its star and country. The episode immediately after the pilot, "Diversity Day" — in which Michael gets in trouble for wanting to perform the Chris Rock routine about the difference between black people and, um, other black people — remains one of the show's funniest, most representative episodes. The Michael Scott in it is still a pretty insufferable character, but there's now a context for him. And the Jim subplot — where he loses his biggest sale of the year but judges the day a success because Pam fell asleep on his shoulder during a long meeting in the conference room — also set a template for how the show could advance that storyline with minimal screen time and the tiniest of baby steps.

When the show returned in the fall, Michael had a better haircut, and the series began a subtle charm offensive on his behalf. The season premiere, "The Dundies," finds Michael dragging the staff through an annual awards ceremony that only he enjoys, only for Jim and a drunk Pam to stick up for him when other Chili's patrons start heckling him — Michael was a jerk, but he was their jerk. "The Client" had Michael pull off the miracle sale in front of Jan, and "Booze Cruise" saw Michael push Jim to keep pursuing Pam even though she was engaged. Slowly but surely, the writers and Carell transformed Michael and his relationship with the staff to the point that it felt believable that they would serenade him at his last Dundies with a rewritten version of "Seasons of Love" from "Rent." Or, earlier, that we would root aggressively for Michael to win a negotiation with his boss — and that he could:



That shift in the character and perception of him was, wisely, a process years in the making. Michael softened just a bit, but he was still capable of being an extreme — and hilarious — dolt. Consider this monologue from "The Injury," which is pound-for-pound the funniest episode the show ever did:



But even with the innately likable Carell playing him, writing for Michael was like navigating a minefield. In many episodes, the show thrillingly made it safely to the other side. From time to time, though, his behavior was too stupid and/or selfish that the show blew up around him. (I cringe just thinking about Michael ruining the college dreams of a bunch of teenagers in "Scott's Tots," for instance, or his toast in "Phyllis' Wedding.")  Sometimes, the extremes could exist within the same episode, like season 2's "Christmas Party"(*), which features a long, uncomfortable sequence where Michael turns the office Secret Santa tradition into a Yankee Swap because he's not happy with the gift he got.

(*) "Christmas Party" was another of the show's commercial turning points, as it was the first episode of the series released on iTunes. (Coincidentally, the big prize of the Secret Santa'ing was a video iPod.) The show's young, tech-savvy audience quickly took to the idea of downloading episodes, which created an additional revenue stream for NBC to consider in its renewal decisions, even if the iTunes audience (and, later, the Hulu and Netflix audience) ate into the numbers of people willing to watch episodes on NBC itself.

And not helping things was that every writer on Daniels' staff — a talented bunch of people who have spread out to work on their own (including Schur on "Parks," Mindy Kaling and B.J. Novak on "The Mindy Project" and Lee Eisenberg and Gene Stupnitsky on a variety of projects, including an upcoming HBO comedy "Hello Ladies" done in collaboration with Stephen Merchant) — seemed to have a slightly different perspective on what kind of Michael was in-character, acceptable and funny. And so did many of the show's fans. For some, the startlingly uncomfortable fight between Michael and Jan during season 4's "Dinner Party" represents everything the show could aspire to; for others, it's an episode you never want to watch again. (I've even heard passionate arguments in defense of "Scott's Tots.") Carell was so versatile that he could play any version of Michael and make it feel like the same character — and his Daniels-penned farewell episode, "Goodbye, Michael," somehow incorporated all those different interpretations into a single episode — but it lent the series an unpredictable, uneven feeling even in its best years.

The Jim/Pam romance was more consistent in terms of what was on screen and how the two of them were portrayed, but was also subject to wildly different expectations among the show's audience. Some watched only for Jim and Pam, and viewed Michael, Dwight and the others as the cost of admission. Some wanted them to get together immediately, while others wanted the exquisite agony of their near-misses to go on for years. (This was an argument that also went on in the writer's room, until Daniels insisted on having them kiss at the end of the second season; by the start of the fourth, they were regularly dating and have stayed together ever since, despite some rocky times in this final season.) Some viewers identified so closely with (or were so attracted to) the initial, mousey incarnation of Pam that they resented her when she became happier and more assertive in the show's later years.



Still, their story moved forward, and for quite a while "The Office" was able to put the lie to the idea that happy couples kill comedies. In particular, their wedding — another one disrupted by Michael Scott, but this time anticipated by Jim — beautifully paid off years of build-up in both their romance and their dealings with their boss:



Because the series was such a volatile mixture of elements, it could veer wildly in quality from week-to-week. The episode after Jim and Pam's wedding, "Mafia," with Michael, Dwight and Andy terrified that a visiting salesman is a representative of organized crime, is one of the dumbest, broadest half-hours the show ever did; the next one, "The Lover," in which Pam is horrified to realize Michael has been sleeping with her mom since the wedding, is one of the best examples of the show mining laughter out of humiliation.

Carell as Michael always provided a safety net. There could be rough patches as the show headed into middle age, but Michael was always around to fuel a funny individual story like Michael and future wife Holly being wildly inappropriate with their office PDAs. And you could even build entire arcs around him, like his spiteful departure from Dunder Mifflin to start The Michael Scott Paper Company. When Carell left late in season 7, the show almost certainly should have ended. Without him, there were ill-conceived new characters like James Spader's aloof Robert California, while other characters were unconvincingly shoehorned into new roles. Ed Helms' Andy was transformed more and more into a tamer version of Michael, along the way illustrating just how good Carell had been, and how well-written (if inconsistently written) Michael was.

Yet even in this problematic final seasons, there have been those weeks when the elements came together in perfect balance. Last week's penultimate episode, "A.A.R.M.," finally had Dwight as the full-time branch manager, and Jim amusing the heck out of himself as Dwight's number two. The dynamic between these former rivals was such a delight that large chunks of the episode (pretty much anything not involving Andy) evoked the series' better days, and suggested a promising road unfortunately not taken after Michael and Holly moved to Colorado.

That the series has been a shadow of itself for much of the last two years shouldn't diminish its earlier greatness. Rare is the comedy that runs this long and stays good all the way to the end. And with a show this volatile, it's a wonder it was great for as long as it was. (I would argue through season 5, and then with some extended highlights as Holly returned in season 7 and Michael prepared to leave.)

It's a show that, through both the main characters and the larger ensemble of office workers like Stanley and Phyllis, expertly captured the crushing ennui — and occasional diversions like Office Olympics and Pretzel Day — of a job that no one dreams of, but that somehow became a career for these people. It's a show that was capable of gasp-inducing comic set pieces like Dwight's fire drill that kicked off the series' post-Super Bowl episode:



It gave us ridiculous but memorable recurring and supporting characters like Dwight's cousin Mose or Creed Bratton as a deranged version of himself. It made our hearts leap when Jim confessed his feelings to Pam, or when he proposed marriage at a highway rest stop. It turned juvenile, creepy, disgusting Michael Scott into a romantic hero whom many viewers wanted to see get the girl in the end.

It did one great, impossible thing after another. Frequently, it succeeded beyond what we could have expected and crafted scenes and episodes destined to be played whenever the history of TV comedy is examined. Occasionally, it failed so spectacularly that a viewer who saw only one of those episodes could be forgiven for wondering why in the world anyone watched or liked this mess.

Michael Scott should not have been able to accomplish the many amazing things that he did at that branch, just as "The Office" had no business being so strong for so long.

That's what she said — whoever "she" is.

Alan Sepinwall may be reached at sepinwall@hitfix.com