Theresa May ended the call just before 11:30pm last Thursday, knowing the future shape of Brexit and even the fate of her government would depend on what she did next. She looked at the grey-faced officials, who had spent three gruelling weeks negotiating the final text of the UK’s divorce deal with the EU. She had not received the green light on the Irish issue that they so desperately wanted. But she decided to push ahead, anyway. “OK,” Mrs May said. “We’re going to go.”

It was one of the biggest judgment calls of her premiership, made against the dull thud of a disco upstairs at the Downing Street Christmas party, and while she was surrounded by discarded plates and half-eaten canapés.

Earlier that evening the prime minister joked about singing “Come on Arlene” at the karaoke. But Arlene Foster, leader of the Democratic Unionist party, was not in a party mood. Speaking from her home in Enniskillen in Northern Ireland’s border country, she remained fiercely sceptical of the fudge being cooked up in London and Dublin on the future of the province.

That late-night call to County Fermanagh marked a coda to a three-week political thriller, a race to a Brexit deal with fateful misunderstandings, sleepless diplomacy and brutal brinkmanship. Agreement had been secured, ending the fraught first phase of EU exit talks. But the fumbled execution almost brought Mrs May’s government crashing down. With EU leaders set to endorse the historic divorce pact at a summit on Friday, the Financial Times has interviewed more than a dozen key participants who helped cut the deal — then rescue it from the brink.

Key dates 1: The Florence speech © Reuters Sept 22 Theresa May lays out a more pragmatic approach to Brexit, including at least €20bn of payments for a two-year transition. Against UK expectations, this is insufficient to open trade talks. 2: Sixth round of formal talks ends © AFP Nov 9-10 The final round of formal negotiations made barely any progress. Trust between the EU and UK side is damaged after the misunderstanding caused by the Florence speech.

It was no mean feat. Mrs Foster’s negotiating experience included head-to-heads with Gerry Kelly, a senior figure from the Sinn Féin nationalist party who once escaped from the Maze prison and spent two weeks lying under the floorboards of a safe house. The DUP leader, who as a teenager was on a school bus bombed by the IRA, was not about to give in easily to Mrs May.

She was accustomed to pushing her negotiating partners up against a deadline, as Mrs May well knew. On Monday December 4, Mrs Foster had torpedoed a draft agreement while Mrs May was in Brussels trying to conclude the deal. Later that night the DUP made clear how far their concerns went: the confidence-and-supply arrangement underpinning Mrs May’s governing majority in the House of Commons was at stake.

By the time of that climactic call on Thursday, though, Mrs May insisted there was no time left. She had to be in Brussels by the following morning; the first big breakthrough in Brexit talks depended on it.

“There were no cross words,” says one of those briefed on the call. “They ended the conversation amicably, but it was still not clear that she had political support [from the DUP] for what she was doing.”

Mrs May headed home to Berkshire shortly after midnight for a few hours of sleep before returning to London for a 4am flight from RAF Northolt. The Downing Street team was still talking to the DUP and Dublin in the early hours: they only called senior EU officials at around 2am Brussels time to confirm that they would be coming.

“When she got on the plane it was clear she was still taking a considerable political risk,” says one ally. Mrs Foster’s DUP could pull the plug on Mrs May’s minority Tory government at any moment. By 7:30am in Brussels the deal was done, with Mrs Foster unhappy, but holding fire.

Key dates 3: ‘Constant contact’ © AFP Nov 15-Dec 1 Negotiations go under the radar, with almost daily talks out of the public glare. Financial issues are resolved first, with a crucial offer made by the UK on November 23. The final week of November primarily relates to Ireland. 4: The failed lunch © EPA Dec 4 The text on Northern Ireland is all but agreed on Monday morning, before Mrs May’s planned lunch with Jean-Claude Juncker, the European Commission president. Objections from Northern Ireland unionists force the prime minister to abort.

It was a frosty mid-November morning in Sweden when the two principal Brexit divorce challenges — money and Ireland — flipped in order of difficulty. Fists clenched, her knuckles white from frustration, Mrs May was meeting the man whose demands were to blindside her Brexit plans: Leo Varadkar, Ireland’s 38-year-old premier. The venue was an old mechanical workshop in Gothenburg; the mood what one senior official calls “the opposite of personal chemistry”.

Mr Varadkar insisted he would not be the Taoiseach to redivide the island. Since the UK had unilaterally ruled out staying in the single market and customs union, he said he would use Ireland’s veto to “take the hard border off the table”. He also demanded written guarantees from Mrs May to avoid such an outcome. Both were leaders managing fragile minority governments, with deeply intertwined national interests. But for 30 painfully awkward minutes, the two premiers talked completely past each other.

British officials left incredulous that Dublin would threaten to scupper a planned Brexit divorce deal in December by asking for the impossible: a promise to potentially keep Northern Ireland pinned to the EU’s rules and customs regime, even as Brexit Britain diverged. The Irish side, meanwhile, departed furious at London’s complacency at imagining everything could be solved by a future EU-UK trade deal .

“Sometimes it doesn’t seem like they have thought all this through,” Mr Varadkar said later that morning.

The irony was that Mrs May had travelled to Gothenburg that Friday to activate a plan to overcome what had been considered the biggest obstacle to a deal: a divorce bill of up to €60bn. Later that afternoon, while attending a summit on social policy, she hinted to Donald Tusk, the European Council president, that Britain was ready to pay up. At the same time, she scheduled a make-or-break December 4 meeting in Brussels with Jean-Claude Juncker, the European Commission president. The endgame was in sight.

Olly Robbins, the Whitehall official leading Brexit talks © Bloomberg

By Monday November 20, Mrs May had secured cabinet support to increase the UK’s offer to essentially honour in full Britain’s share of EU liabilities. The prime minister found she had ample political space: mainstream Conservative Eurosceptics were backing her to clinch a December deal. Downing Street was determined not to repeat the mistake of Mrs May’s Florence speech, which made a halfway offer of €20bn that fell short for Berlin and Paris.

Within days Olly Robbins, a Whitehall official leading negotiations for Mrs May, made the overture in Brussels. When the terms were explained to EU member states in a secret briefing, even the biggest hawks were silenced: the UK would cover all payments that fall due from up to €100bn of gross liabilities. No EU member state would need to contribute a euro more into the EU budget as a result of Britain’s exit.

Having agreed on the substance, the urgent negotiation turned to presentation. While the final Brexit bill would not be known for decades to come, British negotiators wanted to announce a low headline estimate for the net cost: around €40bn-€45bn, rather than the commission’s €50bn-€60bn. They also wanted the commission to say assumptions made by the UK that would minimise payments were reasonable.

The most significant trick was simpler: using front-loaded payments in January-April 2019, the last three months of Britain’s membership, to lower the headline exit bill. That alone reduced the EU estimates of the bill by €4bn-€5bn, according to officials involved in the talks. “We don’t mind if they pay early,” joked one senior EU diplomat.

Key dates 5: DUP face-off © Getty Dec 7 British and Irish negotiators provisionally ​agree a text by the late afternoon. Mrs May’s team is in constant contact with the DUP. The PM makes crucial calls to Arlene Foster, DUP leader, at around 9.30pm and 11.30pm. Negotiations continue through the early hours. 6: Deal day Theresa May heads to Brussels in the early hours of December 8 Dec 8 The joint text is changed after four days of intense negotiations with the DUP and Dublin. Mrs May makes a late-night decision to head to Brussels, even without explicit DUP support. The deal is concluded by 7.30am.

Just as finance was solved, the issue of the Irish border came to the boil. “She [Mrs May] never saw it coming,” says one senior EU figure closely involved in the talks. “They finally realised it was pointless to hold out on the money and, suddenly, whoosh! Up comes the Irish issue. That was a surprise to everybody, not only the Brits. Suddenly we were all facing the unsolvable problem.”

Mrs May had realised that for cabinet Brexiters, almost any financial deal would be better than no Brexit. Yet bowing to Dublin’s demands was altogether a different matter because they raised questions over the integrity of the UK. Another EU official involved in talks says: “This is the nub of it. Cut away the Brexit bullshit and the fluff and you reach the Irish border.”

Brexit talks rapidly evolved into an Anglo-Irish negotiation, with Sabine Weyand, a seasoned deputy to the EU’s chief Brexit negotiator Michel Barnier, holding the ring. By the week of November 27, Brussels and Dublin had agreed a draft to present to London.

To the shock of the UK’s negotiators, the text had potentially incendiary language requiring Britain to ensure “no regulatory divergence” that would require a north-south hard border or undermine the Good Friday Agreement. The implication: Northern Ireland’s economy would operate on different rules from Britain, a redline issue for the DUP.

Similar language had leaked weeks before. In effect it was a fallback scenario if all other options failed. But British negotiators believed EU assurances that it would not be a requirement for “sufficient progress” in divorce talks. That was one of many misunderstandings that would bedevil the negotiation.

A three-way meeting in Brussels on November 30 proved pivotal. The UK secured significant changes but John Callinan, Mr Varadkar’s envoy, held out for the sentence on “no regulatory divergence”, apparently drafted by the Taoiseach himself. By 11pm Mr Robbins yielded and agreed the text, although he would have to take it to Mrs May.

The Brexit deal discussions in Brussels on December 8 © PA

The EU side suggested it may be important to consult the DUP as well, but Mr Robbins doubted he could show them a draft. If the text were given to one Westminster party, it would need to be shared with all. The Irish side wondered if the “astonishingly scrupulous” approach was a ruse to ram through the final draft. UK officials deny it.

In any event, Mrs May, a strong unionist, immediately rejected the “no divergence” text. “It crossed her red lines, she didn’t even ask the DUP,” says one aide.

Talks resumed over the weekend, with the British side suggesting an alternative: maintaining “full alignment” of rules. EU and Irish lawyers saw no material difference, but for London there was wriggle room to depict this as a looser model, based on equivalence of outcomes rather than harmonised rules.

As Mrs May embarked for her lunch with Mr Juncker the next day, the deal appeared on. First London, then Dublin, confirmed to Brussels that “alignment” was satisfactory. British and EU negotiators disagree on whether the full text was signed off, but spirits were high. The main outstanding question was the role of the European Court of Justice in the special rights given to 3m EU nationals in Britain. “Child’s play,” says a senior figure present.

Yet, before the tarte Tatin and cinnamon-scented ice-cream even emerged, the agreement had unravelled. Although consulted over the weekend, DUP officials only saw a text in the late morning, and partial leaks to Irish broadcaster RTE infuriated them. Mrs Foster duly made a defiant statement.

There was sudden commotion in the corridors. Mr Robbins left the Berlaymont lunch, and when he returned with a message Mrs May’s mood darkened. Texts emerged from the room that “this is not going well”. Mr Juncker and his team retreated to their offices to “give her some time”. After almost 45 minutes making calls, Mrs May realised she would return to London empty-handed.

At a hastily arranged press conference, Mr Juncker publicly threw a protective arm around her, saying Mrs May was a “tough negotiator”. But her weakness was impossible to mask. “It is quite something to stab your prime minister in the back when she is about to do a deal,” says a senior EU figure who saw Mrs May that day. “Not all of us were so sure she would return.”

London’s salvage operation went into action. At the end of four days of frenetic activity, a new paragraph emerged in which the UK promised that “no new regulatory barriers” would emerge along the Irish Sea — a form of east-west alignment to go with the north-south promises. To negotiators, it was a textbook compromise, packed with “impossible contradictions”. But it did the job: Mrs May made “sufficient progress” to open talks on a future relationship, while Mr Varadkar claimed a political victory that sent his poll numbers soaring.

The question is how long it will last. EU negotiators see the UK’s pledges to the DUP as “declaratory” — the UK speaking to itself. But they expect the north-south provisions on “alignment” to become an EU-UK pledge that will be included in a binding withdrawal treaty.

“We are heading for a big collision on this,” says one senior negotiator, who predicted trouble within months. “It is unavoidable. The Irish border is where reality meets Brexit fantasy.”

Other senior figures involved in the process are more sanguine, pointing out that Mrs May’s pragmatism essentially secured her the agreement about a transition. The Irish fudge, in other words, could survive beyond Brexit.

“Sometimes you have an unsolvable problem. But the constellations will change,” says one principal figure in the talks. “By going back to the DUP she has managed to buy a transition of two years. In politics that is an eternity. She is buying a little bit of peace.”